我想在我的指令中使用“controllerAs”选项。让我引用“An AngularJS Style Guide for Closure Users at Google”的推理:
Why? Putting methods and properties directly onto the controller, instead of building up a scope object, fits better with the Google Closure class style. Additionally, using 'controller as' makes it obvious which controller you are accessing when multiple controllers apply to an element. Since there is always a '.' in the bindings, you don't have to worry about prototypal inheritance masking primitives.
但是如果指令具有隔离范围绑定(bind),我可以看到使用这种方法的问题。
angular.module('cmw').directive('fooWidget', function() {
return {
controller: function() {
this.qux = '123';
},
controllerAs: 'fooWidget',
scope: {
bar: '='
},
template: ' {{fooWidget.qux}} {{bar}} '
};
});
在这种情况下,
bar
属性附加到范围,而不是 Controller ,这会导致困惑的不一致情况,应该在不同的地方查找不同的属性。解决此问题的“官方”推荐方法是什么?更新:见GitHub issue对这个。
最佳答案
这在 Angular 1.3 中通过添加 bindToController
得到解决。 directive API 的属性(property).
关于javascript - "controller as"vs 隔离范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23496850/