简体   繁体   English

自定义指令内ngInit的替代方法

[英]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.varundefined ,则我的指令不会将其绑定到隔离的作用域。

<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-initvm.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM