1

这些似乎工作相同。但它们是一样的吗?(注意 $scope.active)

第一:

angular.module('my.controllers', []).controller('MyController', ['$scope', 'myService',
function($scope, myService) {
    $scope.myFilters = myService.myFilters;
    $scope.active = $scope.myFilters.length > 0;
    $scope.$watch(function() {
        return myService.myFilters;
    }, function(newFilters) {
        $scope.myFilters = newFilters;
        $scope.active = $scope.myFilters.length > 0;
    },true);
}]);

第二个:

angular.module('my.controllers', []).controller('MyController', ['$scope', 'myService',
function($scope, myService) {
    $scope.myFilters = myService.myFilters;
    $scope.active = function(){return $scope.myFilters.length > 0};
    $scope.$watch(function() {
        return myService.myFilters;
    }, function(newFilters) {
        $scope.myFilters = newFilters;
    },true);
}]);
4

1 回答 1

1

在第二种情况下在 HTML 中绑定到active时,它将在每个 apply-digest 循环中调用,因为函数的结果在调用之前是未知的。这给了您两个不同之处:在控制器函数运行后的更改$scope.myFilters.length不会反映在第一个场景中的绑定中(如果您不自己更新值),并且会在第二种情况,因为该函数在每个应用摘要循环中至少调用一次。

于 2013-08-10T11:58:41.053 回答