javascript - $watch 不适用于数组

标签 javascript angularjs

我正在观察并数组,如果它发生变化,那么我想调用一个函数

$scope.$watch(
            $scope.aQuestions,
            function fncheckQuesCount(newValue, oldValue) {
                debugger;
                if (newValue === oldValue) {
                    return;
                } 
                else fnGetQues();
            });

这里 $scope.aQuestions 是一个数组

但是当我运行这个时,它显示 newValue 和 oldValue 为未定义。

最佳答案

应该是

$scope.$watch("aQuestions",

或者

$scope.$watch(function (){
        return $scope.aQuestions;
},

这是因为 Angular 需要一种反复检查值是什么的方法。

在您的版本中,您只需传入数组的值(未定义)。值何时改变 Angular 不知道,因为它没有对数组的引用。

关于javascript - $watch 不适用于数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37512645/

相关文章:

javascript - Google 路线箭头或渐变

javascript - 带有 promise 的 Angular 异步上传文件

javascript - AngularJS 名称可用性

javascript - 带有注入(inject)服务的单元测试 Angular Controller

javascript - Angular 模态窗口(UI-路由器/指令)

javascript - 如何根据数组的结果更改html部分的背景颜色

javascript - 动态CSS类属性?

javascript - 检索Leaflet当前的比例值

javascript - 更改子元素的 css 类

javascript - Angular.js 命名空间模块 Controller