我在angular指令中使用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
最佳答案
您在代码中遇到了两个问题。
因此,第一件事,您仅在控制器的初始化上设置了控制器变量direlements
,但是那时该变量是未定义的,因为单击时就对其进行了设置。
因此,您需要一个$ watch来使其保持更新并将$ scope注入到控制器中:
vm.direlements = [];
$scope.$watch(function() {
return vm.datasource;
}, function(oldValue, newValue) {
if(typeof(newValue) !== 'undefined') {
vm.direlements = vm.datasource.elements;
}
});
然后在主控制器内部,将当前电流定义为局部变量,但您希望将其定义为vm变量,因此应使用此变量:
var vm = this;
vm.current = {};
其他所有事情都还可以。
因此,这里是您的完整示例:
http://plnkr.co/edit/sALFVkSPIxVPOS42nOGu?p=preview
关于javascript - Angular Directive(指令) Controller 看不到传递的参数更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44180736/