【问题标题】:In Angular 1.x When "watching" in a directive; why does watching a function that returns a variable act different than just watching the variable?在 Angular 1.x 中“观看”指令时;为什么查看返回变量的函数与仅查看变量的行为不同?
【发布时间】:2018-01-05 18:39:05
【问题描述】:

解释这个问题的最简单方法是使用一些示例代码,所以这里有一个用 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 中的行为方式有关,但我无法理解两者的行为方式有何不同。

感谢您提供的任何见解。

【问题讨论】:

标签: javascript angularjs angularjs-directive closures


【解决方案1】:

scope.$watch的接口根据documentation如下:

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

watchExpressionstringfunction。如果它是string,它会被解释为scope 对象中的路径。假设attributes.foo"test.something",它将监视scope.test.something - 如果它存在。

如果您想观察attributes.foo 的值的变化,您必须使用function,或者将attributes.foo 附加到您的作用域并将"attributes.foo" 作为watchExpression 传递。

【讨论】:

    猜你喜欢
    • 2019-11-23
    • 2018-09-13
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多