在构造函数中将数据从链接发送到模板

时间:2017-06-22 17:40:36

标签: angularjs angularjs-directive

class showHidePassword {
    constructor() {
        'ngInject';
        this.template = '<span ng-class="glyphicon glyphicon-eye-{{iconType}}"></span>';
        this.restrict = 'A';
        this.scope = {};
    }

    $onInit() {
        this.iconType = 'open';
    }

    link(scope, iElement, iAttrs) {

        iElement[0].addEventListener('click', (event) => {
            let passInput = event.toElement.offsetParent.previousElementSibling;
            let typeAttribute = passInput.getAttribute('type');

            if(typeAttribute === 'password') {
                passInput.setAttribute('type', 'text');
            } else {
                passInput.setAttribute('type', 'password');
            }
        });
    }

    static directiveFactory() {
        return new showHidePassword();
    }
}

export default showHidePassword;

所以这是我的指令,我想从构造函数中的模板链接发送iconType,怎么做?你有什么想法吗?

2 个答案:

答案 0 :(得分:0)

添加此内部链接。

scope.iconType ="SomeType";

scope.getIconType = function(){   
   return scope.iconType; 
};

答案 1 :(得分:0)

你的指令有很多问题,不值得修复。

以下是带有显示/隐藏密码按钮的<input>的演示。

<button ng-click="showPassword = !showPassword">Show/Hide Password</button>

<input type=password show-password="showPassword" 
       ng-model="thePassword" />

THE DEMO

angular.module("myApp",[]);

angular.module("myApp").directive("showPassword", function() { 
    return function linkFn(scope, elem, attrs) {
        scope.$watch(attrs.showPassword, function(newValue) {
            if (newValue) {
                elem.attr("type", "text");
            } else {
                elem.attr("type", "password");
            };
        });
    };
});
<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app='myApp'>

    <button ng-click="showPassword = !showPassword">Show/Hide Password</button><br>
    
    <input type=password show-password="showPassword" 
           ng-model="thePassword">
    <hr>
    PASSWORD == {{thePassword}}<br>
    showPassword == {{showPassword}}
</div>