通过复选框单击使用指令更改输入类型

时间:2013-04-18 15:12:04

标签: angularjs angularjs-directive

我的主要目标是通过勾选复选框将密码的输入类型更改为文本。

了解DOM操作应该在指令中完成,并在阅读AngularJS: can't change input type

之后

我盯着我的指示如下(所有代码都包含在jsfiddle

 <div ng-app="SignComponents">
     <bca-sign-up-password> </bca-Sign-Up-Password>
 </div>

但是我还没有让它成功。 。 。有什么建议?我正在以有棱角的方式解决这个问题吗?

谢谢!

3 个答案:

答案 0 :(得分:3)

首先,element.html是一种方法,而不是属性,因此哟覆盖了scope.$watch回调中的函数。其次,每个人(你自己,Angular,浏览器)更容易改变输入类型:

http://jsfiddle.net/K6Qgm/6/

scope.$watch('viewPasswordCheckbox', function (newValue) {
    element.find('input')[1].type = newValue ? 'password' : 'text';
});

编辑:如果你真的需要支持旧版本的IE(上面的工作在9中),你可以渲染输入两次并显示/隐藏它:http://jsfiddle.net/K6Qgm/7/

function (newValue) {
    var show = newValue ? 2 : 1,
        hide = newValue ? 1 : 2,
        elements = element.find('input');
    elements[hide].style.display = 'none';
    elements[show].style.display = '';
});

答案 1 :(得分:2)

使用ng-hideng-show比手动操作更好,对于指令模板可能是这样的:

<div>
  <input
    required
    type="text"
    name="password"
    class="input password"
    placeholder="Password"
    ng-hide="viewPassword"
    ng-model="user.Password"
  >
  <input
    required
    name="password"
    type="password"
    class="input password"
    placeholder="Password"
    ng-show="viewPassword"
    ng-model="user.Password"
  >
  <input type="checkbox" class="btn btn-mini" ng-click="showPassword()">
</div>

链接功能:

var linker = function(scope, element, attrs){
  scope.viewPassword = true;
  scope.showPassword = function(){
    scope.viewPassword = !scope.viewPassword;
  };
};

工作示例plunker

答案 2 :(得分:0)

如何创建2个输入字段,一个输入类型=文本,第二个输入类型=密码指向相同的ng-model = user.password“并使用复选框(showpassword)来控制显示哪个输入。

<input ng-hide="showpassword" type="password" name="password" class="form-control" placeholder="Password"   ng-model="user.password" />
<input ng-show="showpassword" type="text" name="password" class="form-control" ng-model="user.password" />
<input type="checkbox" ng-model="showpassword" ng-checked="false"> Show Password
相关问题