javascript - 需要知道,为什么需要使用$apply

标签 javascript angularjs

我需要知道,为什么我们需要在这里使用 $apply,

var clock = angular.module('clock',[]); 
clock.controller('MyController', function($scope) {
        $scope.clock = new Date();
        var updateClock = function() {
          $scope.clock = new Date();
        };
        setInterval(function() {
          $scope.$apply(updateClock);
          //updateClock()  //why this will not work.
        }, 1000);
        updateClock();
      });

Demo

我知道,当使用 $apply 时:

"The $apply() function executes an expression inside of the Angular context from outside of the Angular framework. For instance, if we implement a setTimeout() or are using a third-party library and we want the event to run inside the Angular context, we must use $apply()." Blockquote

但为什么我们需要在这种情况下使用(我的意思是在 jsfiddle 示例中),因为我在相同的上下文中并且没有使用任何 jQuery 代码或第三方库,

With Out $apply fiddle

调用了函数,但输出反射(reflect)在 View 中,为什么?

最佳答案

阅读以下手册。 :)
https://github.com/angular/angular.js/wiki/When-to-use-$scope.$apply()

//根据评论更新
您需要使用 $interval服务。

关于javascript - 需要知道,为什么需要使用$apply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23464997/

相关文章:

JavaScript/Jquery : Show a hidden div based on a Radio box select

javascript - 如何保持并排图像的纵横比,保持图像相同的高度并在图像之间固定填充?

javascript - 如何从传单上的本地存储和图层组中删除特定项目?

javascript - ionic 侧菜单中的异步工厂

javascript - Angular 将不需要的 anchor 添加到我的网址

javascript - CSS 在 AngularJS 中不动态更新

javascript - 如何将 SVG 附加到 <div>?

javascript - 如何刷新 AddThis Facebook 按钮的共享 URL?

javascript - AngularJS View 未加载

javascript - AngularJS ng-controller 声明