解释这个问题最简单的方法是使用一些示例代码,因此这里有一个用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中闭包的行为有关,但我无法理解两者的行为如何不同。
感谢您提供的任何见解。