在Angular控制器中观察数组更改并更新HTML

时间:2015-07-19 20:13:11

标签: javascript angularjs

我想在Angular控制器内观察数组更改并更新HTML视图。

这是我的控制者:

app.controller("timelineCtrl", function ($scope) {
    $scope.arr=[];
         .
         .
         .
}

这是我的指示:

app.directive('helloWorld', function() {
    return {
        restrict: 'AE',
        replace: true,
        template: '<div> Hello {{arrayItem}} </div>',

        link: function ($scope, element, attrs) {

            $scope.$watch($scope.arr, function(newValues, oldValues) {
                $scope.arrayItem = newValues;
            });

        }
    };
});

我通过按钮点击向阵列添加了一些新值,但我的$watch无法正常工作。我怎么能克服这个?

2 个答案:

答案 0 :(得分:1)

目前你的手表没有触发,因为$ scope.arr变量包含相同的引用 - 对最初的同一个数组的引用,现在只更改了此数组中包含的值。 (这是因为javascript中的数组仅通过引用传递,而不是始终复制的基元)

如果你希望watch更“深入”而不仅仅是检查这个引用,并且也在查找对象内容的变化,你可以添加第三个带有true值的布尔参数:

$scope.$watch(
   '$scope.arr', //expression to watch - can also be a function returning a value
   function(newValues, oldValues) { //function to run on change
     $scope.arrayItem = newValues;
   },
   true //deep watch mode?
);

请注意,观看“深度”可能非常昂贵,因为它会检查每个嵌入对象的每个最后一个属性。如果您只想观看某个元素是否被移除或添加到数组中,您可以使用 $watchCollection ,它只能看到浅层,1层向下,并且性能要好得多。

答案 1 :(得分:0)

你应该在true之后添加function来深入观察阵列,这将会对变量进行深入观察,观察中更改的任何元素都会触发function

<强>标记

<hello-world arr="arr" ></hello-world>

<强>代码

$scope.$watch(attrs.arr, function(newValues, oldValues) {
     $scope.arrayItem = newValues;
}, true);