angularjs - 了解 $watch 的工作原理

标签 angularjs

我试图通过一个例子来理解 $watch 是如何工作的,但它不起作用。在示例中,我正在观看一个名为 favorites 的数组,该数组位于 $scope 内。如果收藏夹数组发生变化,我希望在控制台中写入新值。不确定这是否是使用 $watch 的正确方法。

Controller 代码

var mods = angular.module("listApp",[])
    mods.controller("prodCtlr", function($scope){
            $scope.favorites = ["a", "b", "c", "d"]     

            $scope.delete = function(index){
                $scope.favorites.splice(index,1)
            }

            $scope.$watch(function(){
                return $scope.favorites;
            }, function(newVal, oldVal){

                console.log(newVal);

            })

        }
    );

HTML

        <table class="table table-striped">
           <tr ng-repeat="fav in favorites">
            <td>{{fav}}</td><td><input type="button" class="btn btn-primary" value="Delete!" ng-click="delete($index)" ng-model="fav"></input></td>
            </tr>
       </table>

最佳答案

使用$watchCollection :

$scope.favorites = ["a", "b", "c", "d"];
$scope.dataCount = 4;

$scope.$watchCollection('favorites', function(newFavs, oldFavs) {
  $scope.dataCount = newFavs.length;
});

关于angularjs - 了解 $watch 的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32830323/

相关文章:

javascript - 范围变量未显示

javascript - Angular : Disable button if value exist in object array with ng-repeat

javascript - Angularjs 按对象结果拆分数组

javascript - socket.io 回调函数不起作用

javascript - AngularJS 中的多条件过滤器

javascript - JADE 和 ng 类

javascript - 拼写错误或缺少模块?

javascript - AngularJS - 在两个容器内滚动 -anchorScroll

javascript - Angular ng-change 与 ng-model 性能对比

javascript - 为什么嵌入后没有应用 css 样式?