使用angularjs中的可选&符号绑定隔离范围指令?

Pau*_*aul 13 angularjs

可以使用可选的&符号(父上下文)数据绑定创建隔离范围吗?

scope: {
  myMethod: '&?'
}
Run Code Online (Sandbox Code Playgroud)

如果在没有分配myMethod的情况下实现该指令,则没有错误.但是,我看到,当未指定可选属性时,角度无论如何都会为其赋予noop功能.因此,似乎无法在指令中知道实现者是否为可选属性分配了方法.

link: function (scope, element, attrs) {
 scope.myMethod(); //this calls a noop function instead of being undefined, as i exected
}
Run Code Online (Sandbox Code Playgroud)

任何见解?我想知道实现者是否已分配可选属性.

DRi*_*FTy 15

检查attrs对象以查看它是否已填充:

link: function (scope, element, attrs) {
    if (attrs.myMethod) {
        scope.myMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 14

使用'&?' 如果尚未设置属性,则返回undefined.

https://github.com/angular/angular.js/commit/6a38dbfd3c34c8f9efff503d17eb3cbeb666d422