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.
<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.
<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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.