Call function from div with JS angular parameter

Below I am trying to convert a millisecond to a javascript date:

<div ng-app>
  <div ng-controller="TodoCtrl">
    <div>
        <script type="text/javascript">
            parseDate({{test}})
        </script>
      </div>
  </div>
</div>

function TodoCtrl($scope) {
  $scope.test = "1429831430363"
}

function parseDate(date) {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    return months[date.getUTCMonth()] + ' ' + date.getUTCDate();
}

http://jsfiddle.net/U3pVM/15141/

But the error is Uncaught SyntaxError: Unexpected token {thrown to the console.

What is the correct method to call a function from a div with an angularJS parameter?

+4
source share
4 answers

use this code: see fiddle

<div ng-app>
  <div ng-controller="TodoCtrl">
    <div>
      {{parseDate(test)}}
      </div>
  </div>
</div>


function TodoCtrl($scope) {
  $scope.test = "1429831430363"

    $scope.parseDate=function(date) {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    return months[(new Date()).getUTCMonth()] + ' ' + (new Date()).getUTCDate();
   }
}
+2
source

A more elegant date formatting solution is to create a custom filter because it is cleaner and you can reuse it everywhere:

Filter:

myApp.filter('myMillisecondsToUTCDate', [function() {
    return function(milliseconds) {
        var date = new Date(milliseconds);
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        return months[date.getUTCMonth()] + ' ' + date.getUTCDate();
    };
}]);

Controller:

myApp.controller('MyCtrl', function($scope, $filter) {
    $scope.testDate = 1429831430363;   
    // Re-Use the filter everywhere
    $scope.formattedDate = $filter('myMillisecondsToUTCDate')($scope.testDate);
});

Html:

<div ng-controller="MyCtrl">
    Format a date using a custom filter: {{testDate | myMillisecondsToUTCDate}}<br/>
    Formatted date {{formattedDate}}
</div>

Check out the demo script

+1
source

angular.element jqLite.scope . , angular , parseDate .

parseDate(
  angular
    .element('[ng-controller="TodoCtrl"]') // but you'd rather give it an ID / class name / whatever
    .scope()
    .test
);
0

:

  • script div, - .

  • parseDate angularjs. , / factory . angular.

  • - . getUTCMonth, , , .

, :

    <div ng-app>
  <div ng-controller="TodoCtrl">
    <div>
            {{parseDate(test)}}
      </div>
  </div>
</div>

:

function TodoCtrl($scope) {
  $scope.test = 1429831430363;
  $scope.parseDate = function(date) {
  var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  date = new Date(date);
  return months[date.getUTCMonth()] + ' ' + date.getUTCDate();
}
}

: http://jsfiddle.net/U3pVM/15146/

0

Source: https://habr.com/ru/post/1584611/


All Articles