简体   繁体   English

AngularJS:指令监视属性表达式

[英]AngularJS : directive watch attribute expression

I want a directive to watch the result of an attribute expression such as: 我想要一个指令来观察属性表达式的结果,例如:

<div scroll-if="test === selectedTest"></div>

So that it can then react to the change and scroll to the particular element. 这样它就可以对变化作出反应并滚动到特定元素。 I seem to be struggling to find out how I can watch for changes to that expression. 我似乎在努力寻找如何观察这种表达方式的变化。

Use $watch : 使用$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);
    }
  }
});

$watch can evaluate the attribute expression scroll-if , the actionScroll listener will run if this expression is true. $watch可以评估属性表达式scroll-if ,如果此表达式为true,则actionScroll侦听器将运行。

Is necessary to add the condition newVal!==oldVal , because actionScroll always runs the first time. 有必要添加条件newVal!==oldVal ,因为actionScroll总是第一次运行。 This is explained in the $watch documentation 这在$ watch文档中有解释

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM