我正在努力使角度指令与 controllerAs 一起使用。当使用$ scope时,一切都按预期工作,但是当摆脱$ scope指令控制器不起作用。请参阅下面的代码和plunker:http://plnkr.co/edit/o3F4lUrxL4mK1DWSYsad。为什么单击按钮时不显示该值?
<body ng-app="myApp">
<div ng-controller="TestCtrl as test">
<button ng-click="test.buttonClick()">push me</button>
<test-directive datasource="test.current"></test-directive>
</div>
</body>
angular.module('myApp', [])
.directive('testDirective', function() {
var controller = function() {
console.log(this);
};
return {
controller: controller,
controllerAs: 'vm',
bindToController: true,
scope: {
datasource: '=',
},
template: '<div>{{vm.somekey}}</div>'
}
})
.controller('TestCtrl', function() {
var vm = this,
current = {};
vm.buttonClick = function() {
console.log('buttonClick');
vm.current = {
somekey: 'somevalue'
}
}
});
答案 0 :(得分:3)
应该是:PLNKR
// Code goes here
angular.module('myApp', [])
.directive('testDirective', function() {
var controller = function() {
console.log(this);
};
return {
controller: controller,
controllerAs: 'vm',
bindToController: true,
scope: {
datasource: '=',
},
template: '<div>{{vm.datasource.somekey}}</div>'
}
})
.controller('TestCtrl', function() {
var vm = this,
current = {};
vm.buttonClick = function() {
console.log('buttonClick');
vm.current = {
somekey: 'somevalue'
}
}
});
刚刚更改了&#34; vm.datasource.somekey&#34;