AngularJS:指令监视属性表达式

Ben*_*awk 4 javascript watch angularjs angularjs-directive

我想要一个指令来观察属性表达式的结果,例如:

<div scroll-if="test === selectedTest"></div>
Run Code Online (Sandbox Code Playgroud)

这样它就可以对变化作出反应并滚动到特定元素.我似乎在努力寻找如何观察表达方式的变化.

Car*_*ero 8

用途$watch:

app.directive('scrollIf', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attributes) {

      var actionScroll = function(newVal, oldVal) {
        if(newVal!==oldVal) {
          console.log("scrolling");
        }
      }

      scope.$watch(attributes.scrollIf, actionScroll);
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

$watch可以评估属性表达式scroll-if,actionScroll如果此表达式为true ,则侦听器将运行.

有必要添加条件newVal!==oldVal,因为actionScroll总是第一次运行.这在$ watch文档中有解释