AngularJS $scope.$watch在指令内部对json对象的监视不起作用。

13 浏览
0 Comments

AngularJS $scope.$watch在指令内部对json对象的监视不起作用。

我在这里错过了一些明显的东西。在我的指令中,我有一个工作的双向数据绑定,但是我似乎无法使用$scope.$watch()来监视可能发生在指令的父级作用域js对象上的变化。\n正如你所看到的,当我尝试在attrs.dirModel上使用$watch时,结果的值是undefined,并且没有进一步的监视,即使我在短暂的延迟后修改了对象。我还尝试在$watch语句上使用(或不使用)true标志。\nHTML:\n



    
    {{model.tbdTwoWayPropA}}

\nJS:\n

var app = angular.module('test', []);
app.controller("MainCtrl", [
    "$scope", "$timeout",
    function($scope, $timeout){
        $scope.model = {
            tbdTwoWayPropA: undefined,
            tbdTwoWayPropB: undefined,
            tbdTwoWayPropC: undefined
        }
        // TBD Ajax call
        $timeout(function(){
            // alert("Model updated, but $scope.$watch isn't seeing it.");
            $scope.model.tbdTwoWayPropA = 1;
            $scope.model.tbdTwoWayPropB = 30;
            $scope.model.tbdTwoWayPropC = [{ a: 1 },{ a: 2 },{ a: 3 }];
        }, 2000)
    }
]);
app.directive('dir', [
  "$timeout",
  function($timeout) {
      return {
          restrict: "E",
          controller: function($scope){
              $scope.modifyTwoWayBindings = function(){
                  // Two-way bind works
                  $scope.dirModel.tbdTwoWayPropA = 2;
              }
              $timeout(function(){
                  $scope.modifyTwoWayBindings();
              }, 4000);
          },
          scope: {
              dirModel: '='
          },
          template: $("#template").html(),
          replace: true,
          link: function($scope, element, attrs) { 
            $scope.$watch( attrs.dirModel, handleModelUpdate, true);
              // alert(attrs.dirModel);
              function handleModelUpdate(newModel, oldModel, $scope) {
                  alert('Trying to watch mutations on the parent js object: ' + newModel);
              }
          }
      }
}]);

0
0 Comments

问题的出现原因是使用了'=',导致有一个本地指令作用域属性dirModel。只需$watch它即可。

解决方法是使用$scope.$watch('dirModel', handleModelUpdate, true)来监听dirModel的变化。

关于"本地指令作用域属性"的更多学习资源可以在AngularJS的directive文档中找到。同时也可以参考stackoverflow上相关的问题,如“what is the difference between and in directive scope”、“what is the difference between vs and in angularjs”以及“what are the nuances of scope prototypal prototypical inheritance in angularjs”。

需要注意的是,$watch是Scope对象上定义的方法,如果$watch的第一个参数是一个字符串,它会根据该字符串在作用域上进行求值。$watch只能观察作用域属性的变化(或者可以给它提供一个函数来观察)。而$observe()和$set是Attributes对象上的方法,它们只能观察/设置属性的值(使用标准化的属性名)。

0