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> 

1 Answer 1

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="[email protected]" 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>

Sign up to request clarification or add additional context in comments.

2 Comments

it working correctly on browser but not working on device iphone. show invalid date .new date ("2017-12-19 22:00:00") show invaliid
use new Date() not new date() . Also, Safari won't recognize that string as valid time format as described here - stackoverflow.com/questions/3085937/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.