element.on("点击",...)不要触发$ watch

时间:2014-05-27 20:25:40

标签: angularjs onclick watch

为什么点击事件不会在下面的代码中触发$ watch?如果我加入$apply,则会触发$ watch。

angulartest.factory("Fac", function () {
  var v = "foo";
  return {
    getV: function () {
      return v;
    },  
    setV: function (v_) {
      v = v_; 
    }   
  };  
});

angulartest.directive("wdirective", function (Fac) {
  return {
    restrict: "E",
    template: "<p>Hello</p>",
    link: function (scope, element, attrs) {
      element.on("click", function (event) {
        Fac.setV("bar");
        //scope.$apply();  <-- Need this to fire $watch
      }); 
    }   
  };  
});

angulartest.controller("wController", function($scope, Fac) {

  $scope.$watch(Fac.getV, function(newValue, oldValue) {
    console.log("v = " + newValue);
  }); 

});

1 个答案:

答案 0 :(得分:1)

因为Angulars $digest周期不是由纯JS点击事件触发的。