2

Here is my code. function defined in controller called in html but console many times.

In controller:

$scope.test=function(r)
{
    var strDateTime = r+" GMT";
    var myDate = new Date(strDateTime);
    console.dir(myDate.toLocaleString());
    return myDate.toLocaleString();
}

Within HTML I am calling function like this:

<div>{{test("2017-12-19 22:00:00")}}</div>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
shiv nayak
  • 143
  • 9

1 Answers1

1

It's better to use a custom filter (pipe) , as calling a scope method like in your example will get evaluated multiple time.

Angular expressions ({{expression}}) are re-evaluated on each $digest loop (sometimes multiple times per loop).

Example below:

const customDate = ()=>{
   return (str)=>{
    var strDateTime = str+" GMT";
    var myDate = new Date(strDateTime);
    return myDate.toLocaleString();
  }
}
var app = angular.module('app', []).filter('customDate', customDate);

app.controller('mainController', function($scope, $http) {
    $scope.datestring = "2017-12-19 22:00:00"
  
})
 <script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.8/angular.min.js" data-semver="1.5.8"></script> 
<div ng-app="app">
  <div ng-controller="mainController">
   <div>{{ datestring | customDate }}</div>
  </div>
</div>
mike_t
  • 2,484
  • 2
  • 21
  • 39
  • it working correctly on browser but not working on device iphone. show invalid date .new date ("2017-12-19 22:00:00") show invaliid – shiv nayak Dec 20 '17 at 10:08
  • use `new Date()` not `new date()` . Also, Safari won't recognize that string as valid time format as described here - https://stackoverflow.com/questions/3085937/safari-js-cannot-parse-yyyy-mm-dd-date-format – mike_t Dec 20 '17 at 10:37