angular 带有控制器的指令不起作用
angular directive with controllerAs dosn't work
我正在努力使 angular 指令与 controllerAs 一起工作。当使用 $scope 时,一切都按预期工作,但是当摆脱 $scope 指令时,控制器不起作用。请查看下面的代码并插入: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'
}
}
});
应该是: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'
}
}
});
刚刚更改"vm.datasource.somekey"
我正在努力使 angular 指令与 controllerAs 一起工作。当使用 $scope 时,一切都按预期工作,但是当摆脱 $scope 指令时,控制器不起作用。请查看下面的代码并插入: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'
}
}
});
应该是: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'
}
}
});
刚刚更改"vm.datasource.somekey"