AngularJs - 使用指令在点击事件上显示隐藏密码

oju*_*rni 1 angularjs angularjs-directive

我现在有一个密码输入字段和一个带有该输入字段的按钮
,如果输入字段的类型是密码,即type="password",然后单击该按钮,它应该变成文本type="text"
即如果我再次单击同一个按钮,它应该更改type="password"

意味着它应该切换value输入元素的类型

我已经使用控制器完成了此操作,它与控制器一起工作正常。下面是使用控制器的工作代码

但是如果我想使用指令而不是控制器,那么如何使用指令处理此切换条件

目的 - 我想在多个输入元素上使用此功能

超文本标记语言

<div class="input-group">
   <label>Password</label>
   <input type="{{inputType}}" class="form-control" ng-model="password" />
   <span ng-click="show()">show</span>
</div>
Run Code Online (Sandbox Code Playgroud)

控制器

$scope.inputType = 'password';

$scope.show = function() {
  if ($scope.inputType === 'password') {
     $scope.inputType = !$scope.inputType;
     $scope.inputType = 'text';
  } else {
     $scope.inputType = !$scope.inputType;
     $scope.inputType = 'password';
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用指令 - 下面是我的试用代码,
我不知道如何<input />使用指令更改元素的类型

指示

.directive('myDir', function() {
    require: 'ngModel',
    link: function (scope, element, attrs) {
       console.log(attrs.type);
       attrs.type = 'password'

      // how to call this below code on click event or on click of <span>  
         which I am using for password

       if (attrs.type === 'password') {
          attrs.type = !attrs.type;
          attrs.type = 'text';
       } else {
          attrs.type = !attrs.type.inputType;
          attrs.type = 'password';
       }
    }
})
Run Code Online (Sandbox Code Playgroud)

HTML 使用指令

<div class="input-group">
   <label>Password</label>
   <input my-dir type="" class="form-control" ng-model="password" />
   <span ng-click="show()">show</span>
</div>
Run Code Online (Sandbox Code Playgroud)

Gau*_*rav 5

您可以使用 ng-attr-type 指令动态更改输入类型。例如:

<input ng-attr-type="{{ isPassword ? 'password' : 'text' }}">
Run Code Online (Sandbox Code Playgroud)

isPassword 您可以更改单击事件的值并使其切换。

使用指令

.directive('isPassword', function() {
  return {
    restrict : 'A', 
    scope: {
      isPassword: '=isPassword'
    },
    link: function (scope, element, attrs) {
       scope.$watch('isPassword', function(a, b){
         element.attr('type', a ? 'password' : 'text')
       })
    }
  }
});

<input is-password="checkPassword" placeholder="Put your password" />

<input type="checkbox" ng-model="checkPassword" />
Run Code Online (Sandbox Code Playgroud)

单击按钮更新

<button ng-click="checkPassword=!checkPassword">click</button>
Run Code Online (Sandbox Code Playgroud)