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

时间:2017-04-14 11:00:19

标签: angularjs angularjs-directive

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

表示应该切换输入元素类型的value

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

但如果我想使用指令,那么如何使用指令

来处理这种切换条件,而不是控制器

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

HTML

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

控制器

$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';
  }
}

我尝试使用指令 - 下面是我的试用代码
我没有得到如何使用指令

更改<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';
       }
    }
})

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>

2 个答案:

答案 0 :(得分:3)

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

<input ng-attr-type="{{ isPassword ? 'password' : 'text' }}">

您可以将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" />

点击按钮更新

<button ng-click="checkPassword=!checkPassword">click</button>

答案 1 :(得分:2)

这是以下指令在添加到input元素时所执行的操作。

  1. 它附加了一个span元素&#34; Show me&#34;附加ng-click=show()事件。
  2. scope: true启用指令的隔离范围。这可确保函数show()对于每个指令都是唯一的。
  3. 当点击&#34;显示我&#34;时,该指令会更改该元素的输入类型。
  4. 希望这有帮助。

    JSfiddle link