代码之家  ›  专栏  ›  技术社区  ›  Bill Rawlinson

在角度1中。在指令中“监视”时为x;为什么观察返回变量的函数的行为与只观察变量的行为不同?

  •  1
  • Bill Rawlinson  · 技术社区  · 8 年前

    解释这个问题最简单的方法是使用一些示例代码,因此这里有一个用ES6语法编写的非常简单的指令:

    export default class IsFoo {
    
      constructor() {
        // Set the directive properties
        this.restrict = 'A';
        this.require = 'ngModel';
      }
    
      link(scope, element, attributes, controller) {
    
        let foo = scope.$eval(attributes.foo);
    
        controller.$validators.isFooBar = (modelValue) => {
    
          // make sure we have the most recent value foo
          foo = attributes.foo;
    
            return foo === 'bar';
          };
    
          scope.$watch(() => {return attributes.foo;}, () => controller.$validate());
      }
    
      static directiveFactory() {
        IsFoo.instance = new IsFoo();
        return IsFoo.instance;
      }
    
    }
    
    IsFoo.directiveName = 'isFooBar';
    

    这是我指令的粗略版本,删除了所有实际的重要验证。。这很简单。

    如果我将观察线更改为:

    scope.$watch(attributes.foo), ()=>controller.$validate());
    

    它不起作用。为什么?为什么函数返回 attributes.foo 工作

    导致最终结果不同的差异是什么?

    此外,免责声明,我有意不使用范围隔离,因为该指令正在具有另一个使用范围隔离的指令的元素上使用。。所以它们发生碰撞,你会得到一个错误 Multiple directives asking for new/isolated scope on: xxx .

    我的粗略猜测是,这与javascript中闭包的行为有关,但我无法理解两者的行为如何不同。

    感谢您提供的任何见解。

    1 回复  |  直到 8 年前
        1
  •  1
  •   JanS Aymeric Brudey    8 年前

    的接口 scope.$watch 是根据 documentation 以下内容:

    $watch(watchExpression, listener, [objectEquality]);
    

    具有 watchExpression 要么是 string 或a function . 如果是 一串 ,它被解释为 scope 对象假设 attributes.foo 是 "test.something" ,它将观看 scope.test.something -如果存在。

    如果要监视 属性。foo公司 ,您必须使用 作用 ,或附加 属性。foo公司 你的范围和通行证 "attributes.foo" 像 watchExpression .