我在角度指令中使用 controllerAs 时遇到问题。当数据作为参数传递给指令时,我想做一些简单的转换并将其传递给子指令。初始化参数为空。它通过 ng-click 事件传递。
angular.module('myApp', [])
.directive('testDirective', function() {
var controller = function() {
var vm = this;
// when 'datasoure' is bound to the controller?
console.log(vm);
// I have to do some transformations here when the data is pushed to the directive
if (vm.datasource != undefined) {
vm.direlements = vm.datasource.elements;
}
};
return {
controller: controller,
controllerAs: 'ctrl',
bindToController: true,
scope: {
datasource: '=',
},
template: '<div><li ng-repeat="item in ctrl.direlements">{{item}}</li></div>'
}
})
.controller('TestCtrl', function() {
var vm = this,
current = {};
vm.buttonClick = function() {
console.log('buttonClick');
vm.current = {
elements: [{
'a': 1
}, {
'b': 2
}]
}
}
});
HTML:
<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>
这里什么也没有发生。似乎控制器不跟踪参数变化。Plunkr