关于javascript:$ scope.apply()应该在angular中使用吗?

When should $scope.apply() be used in angular?

本问题已经有最佳答案,请猛点这里访问。

$scope.apply做什么?在某些情况下,如果不存在$scope.apply(),则不会触发$scope.watch()。例如,

控制器具有以下功能:

1
2
3
setTimeout(function(){
  $scope.person = someperson;
}, 500);

指令中正在监视人员。

1
2
3
4
$scope.watch('person', function(){
  console.log($scope.person);
  $scope.apply();
});

在这种情况下,只有当存在apply时才会触发watch。


scope.apply美元(美元)将触发回路angularjs of the Digest。is to put简单方便的方式,它只在触发重画to the app。P></

恩,当你想usually is used to run that is a piece of Code of APP在角。P></

直接文件:from theP></

$apply() is used to execute an expression in angular from outside of
the angular framework. (For example from browser DOM events,
setTimeout, XHR or third party libraries). Because we are calling into
the angular framework we need to perform proper scope life cycle of
exception handling, executing watches.

example of using扫帚。apply()美元什么控件:与jQueryP></

1
2
3
4
5
6
7
8
9
10
11
12
13
angular.module('customApp', []).directive('datepicker', function () {
    return {
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            jQuery(element).datepicker({
                onSelect: function (date) {
                    scope.myDate = date;
                    scope.$apply();
                }
            });
        }
    };
});

setTimeout(function(){}:JavaScript函数which is - is out of the scope of You need to apply anuglar JS manually with the help of the Digest周scope.apply(元);P></

你可以使用instead but which is more美元超时服务角的方式。P></


如果你真的angularjs modify an模型(从外部使用JavaScript)- You should apply()美元美元的范围。angularjs让知道模型has changed。你在你的实例使用setTimeout()method which is an external JS异步。不管一个人多angularjs超时如果你使用the need to You Call我也`美元(美元)美元的扫帚。apply。P></