问题描述
我正在尝试遵循约翰·帕帕(John Papa)的angularJS样式指南此处,并已开始切换我的指令使用controllerAs.但是,这不起作用.我的模板似乎无法访问分配给vm的任何内容.请看这个展示行为的非常简单的plnkr示例.
I'm trying to follow John Papa's angularJS style guide here and have started switching my directives to using controllerAs. However, this is not working. My template cannot seem to access anything assigned to vm. See this very simple plnkr example that exhibits the behavior.
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";
}
推荐答案
使用controllerAs语法时,您不像通常那样访问$ scope,变量vm被添加到范围中,因此您的按钮需要变为:
When using the controllerAs syntax you don't access the $scope as you would normally, the variable vm is added to the scope, so your button needs to become:
<button ng-click="click">{{vm.text}}</button>
请注意将vm.
添加到text
的开头.
Notice the vm.
added to the beginning of text
.
Q:您知道我将如何访问作为指令的属性传递的属性,例如"scope:{text:'@'}"?然后我是否被迫在控制器上使用$ scope并设置vm.text = $ scope.text?
A:在您引用的文章中,有一节y075 讨论了这种情况.查看bindToController
:
A: In the article you reference, there is a section y075 that talks about just this scenario. Look into bindToController
:
return {
restrict: 'E',
template: '<button ng-click="click">{{text}}</button>',
controller: testCtrl,
controllerAs: 'vm',
scope: {
text: '@'
},
bindToController: true // because the scope is isolated
};
然后您应该可以访问vm.text
这篇关于结合使用ControllerA和指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!