[英]Alternative for ngInit inside custom directive
Assume I have a simple directive: 假设我有一个简单的指令:
angular.module('app').directive('myDir', myDir);
function myDir() {
var directive = {
bindToController: true,
controller: null,
controllerAs: 'vm',
template: '<button ng-click="vm.myDirVar = 1">',
scope: {
myDirVar: '='
}
};
return directive;
}
If in the following example vm.var
is undefined
, my directive will not bind it to the isolated scope. 如果在以下示例中
vm.var
是undefined
,则我的指令不会将其绑定到隔离的作用域。
<my-dir my-dir-var="vm.var"></my-dir>
So in order to make it work, I'm using ng-init
to set the default value for the vm.var
, after that the binding to isolated scope works. 因此,为了使其正常工作,我使用
ng-init
设置vm.var
的默认值,然后将其绑定到隔离的范围。
<my-dir my-dir-var="vm.var" ng-init="vm.var = var || 0"></my-dir>
The question is, how can I improve my directive so I can get rid of the ng-init
while vm.var
would still be binding even if it is undefined
initially. 问题是,如何改进我的指令,这样我就可以摆脱
ng-init
而vm.var
仍然是绑定的,即使最初undefined
。
You can do something like: 您可以执行以下操作:
var directive = {
bindToController: true,
controller: function(){
this.myDirVar = this.myDirVar || 0;
},
controllerAs: 'vm',
template: '<button ng-click="vm.myDirVar = 1">',
scope: {
myDirVar: '='
}
};
If is not a problem having a controller. 如果有控制器则不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.