javascript - "controller as"vs 隔离范围

标签 javascript angularjs angularjs-directive angularjs-scope angularjs-controller

我想在我的指令中使用“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/

相关文章:

javascript - 如何在jquery中将变量中的值从一个页面发送到另一个页面?

javascript - 如何使用javascript删除div中的空格?

javascript - angularjs如何动态更改模板url

javascript - 如何使用html5获取angularjs中可拖动选项卡的索引值

angularjs - 以 ng-minlength 为单位的动态值

javascript - 使用 CKeditor 工具获取电子邮件上的 HTML 标签后

javascript - 显示带有 angularjs 数据绑定(bind)表单的 Bootstrap 框

javascript - JSON 和 jQuery

javascript - 尝试将对象从客户端发送到服务器(AngularJS $http.post)

javascript - 如何在 AngularJS 中正确使用 HTTP.GET?具体来说,对于外部 API 调用?