使用带有指令的ControllerAs

Rya*_*ton 26 angularjs angularjs-directive angularjs-controlleras

我试图在这里遵循John Papa的angularJS风格指南,并开始将我的指令转换为使用controllerAs.但是,这不起作用.我的模板似乎无法访问分配给vm的任何内容.看到展示行为的这个非常简单的plnkr示例.

http://plnkr.co/edit/bVl1TcxlZLZ7oPCbk8sk?p=preview

angular
    .module('app', []);

angular
    .module('app')
    .directive('test', test);

function test() {
    return {
        restrict: 'E',
        template: '<button ng-click="click">{{text}}</button>',
        controller: testCtrl,
        controllerAs: 'vm'
    }
}

angular
    .module('app')
    .controller('testCtrl', testCtrl);

function testCtrl() {
  var vm = this;
  vm.text = "TEST";
}
Run Code Online (Sandbox Code Playgroud)

Tr1*_*tan 37

当使用controllerAs语法时,您不像通常那样访问$ scope,变量vm被添加到范围中,因此您的按钮需要变为:

<button ng-click="click">{{vm.text}}</button>

注意vm.添加到开头text.

这是你的Plunk的一个分叉,应用了修复


问:您是否知道我将如何访问作为属性传递给属性的属性,例如"scope:{text:'@'}"?我是否被迫在控制器上使用$ scope并设置vm.text = $ scope.text?

答:在你引用的文章中,有一节y075只讨论了这个场景.看看bindToController:

return {
    restrict: 'E',
    template: '<button ng-click="click">{{text}}</button>',
    controller: testCtrl,
    controllerAs: 'vm',
    scope: {
        text: '@'
    },
    bindToController: true // because the scope is isolated
};
Run Code Online (Sandbox Code Playgroud)

然后你应该能够访问 vm.text