【问题标题】:Change input type using directives by checkbox click通过复选框单击使用指令更改输入类型
【发布时间】:2013-04-18 15:12:04
【问题描述】:

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

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

我盯着我的指令如下(jsfiddle 中包含的所有代码)

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

但是我还没有真正让它工作。 . .有什么建议么?我正在以有角度的方式解决它?

谢谢!

【问题讨论】:

  • 我刚刚打开了小提琴。变量范围未知(第 22 行)。你可以先检查一下。
  • 。 . .更新!谢谢@didier_v_!

标签: angularjs angularjs-directive


【解决方案1】:

首先,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 = '';
});

【讨论】:

    【解决方案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

    【讨论】:

      【解决方案3】:

      如何创建 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
      

      【讨论】:

        猜你喜欢
        • 2016-01-20
        • 2020-01-20
        • 2019-12-25
        • 1970-01-01
        • 1970-01-01
        • 2020-10-19
        • 1970-01-01
        • 1970-01-01
        • 2012-02-24
        相关资源
        最近更新 更多