AngularJS notifying view of changes to model

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 06:18:47

问题


I'm trying to display the current time in a view based on a Javascript Date object in my controller. My controller looks like this:

myApp.controller('DateCtrl', function($scope) {
    var date = new Date();
    $scope.minutes = date.getMinutes();
    $scope.hours = date.getHours();
    $scope.seconds = date.getSeconds();
    var updateTime = function() {
        var date2 = new Date();
        $scope.minutes = date2.getMinutes();
        $scope.hours = date2.getHours();
        $scope.seconds = date2.getSeconds();
    }
    $scope.clickUpdate = function() {
        setInterval(updateTime, 1000);
    }
});

In my view I simply have:

<div ng-controller="DateCtrl">
    <div>This is the hour: {{ hours }}</div>
    <div>This is the minute: {{ minutes }}</div>
    <div>This is the second: {{ seconds }}</div>
    <button ng-click="clickUpdate()">Click Update Here!</button>
</div>

For some reason, the setInterval() method works only once and I can't get it to keep running updateTime() every 1 second as was set. I put in a simple console.log() statement and that ran every 1 second...so I'm very confused.

I've also checked out $scope.watch() and $scope.digest() but I'm not quite sure how they can be used/if I'm supposed to use them in this scenario.

EDIT: Upon further inspection, it appears as if the setInterval is working properly, calling updateTime() every 1 second, but the values in the scope aren't being reflected in my view after every call.


回答1:


It's because you are changing the scope from outside the angular world (setInterval). You must $apply the changes:

var updateTime = function() {
    $scope.$apply(function(){
        var date2 = new Date();
        $scope.minutes = date2.getMinutes();
        $scope.hours = date2.getHours();
        $scope.seconds = date2.getSeconds();
    });
}

or use a angular aware function such as $timeout. Check @asgoth answer in this question to create an angular aware setInterval() function.




回答2:


You can also use $scope.$digest() after you change model , but I think $scope.$apply is better



来源:https://stackoverflow.com/questions/17848063/angularjs-notifying-view-of-changes-to-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!