AngularJS:无法更改输入类型

pun*_*und 18 angularjs

Whenver我有一个角表达式作为值inputtype,它不会工作:

<input ng-model="model" type="{{'number'}}">
Run Code Online (Sandbox Code Playgroud)

数字值转换为字符串,复选框根本不起作用.

http://jsfiddle.net/punund/NRRj7/3/

vid*_*uch 30

是的,你可以...至少现在:)

HTML:

<section ng-app="myApp" ng-controller="mainCtrl">
  <input type="{{inputType}}" placeholder="Put your password" />
  <input type="checkbox" id="checkbox" ng-model="passwordCheckbox" ng-click="hideShowPassword()" />
  <label for="checkbox" ng-if="passwordCheckbox">Hide password</label>
  <label for="checkbox" ng-if="!passwordCheckbox">Show password</label>  
</section>
<script src="http://code.angularjs.org/1.2.13/angular.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

JS:

var myApp = angular.module('myApp', []);
myApp.controller('mainCtrl', ['$scope', function( $scope ){

  // Set the default value of inputType
  $scope.inputType = 'password';

  // Hide & show password function
  $scope.hideShowPassword = function(){
    if ($scope.inputType == 'password')
      $scope.inputType = 'text';
    else
      $scope.inputType = 'password';
  };
}]);
Run Code Online (Sandbox Code Playgroud)

来源:http://codepen.io/gymbry/pen/fJchw/

更新2015年4月17日:

我已经在Codepen上面随机改变了Angular版本,这似乎适用于版本1.0.2 ...希望这个帮助......


pko*_*rce 21

您无法动态更改输入的类型,因为IE不允许这样,并且AngularJS需要跨浏览器兼容.因此,即使您可能看到源代码中显示的更改类型,AngularJS也不会选择它 - 类型只会被评估一次而无法更改.

请注意,同样的限制适用于jQuery:jQuery更改输入类型

您只有动态类型的选项可以是自定义指令(您可以在其中下载动态模板或在运行中准备DOM),或者使用ng-include包含输入类型为静态值的包含部分.

  • 我很想看到一些关于创建自定义指令的技巧,看看这个......在这里敲我的头撞墙:) (2认同)

Cha*_*wda 13

您无法在任何浏览器中动态更改输入类型,因此无法使用动态单输入语句.您将使用条件语句来创建type硬编码的元素.

使用ng-switch on指令,您可以type根据条件匹配比较和创建元素.例如:

<div class="form-group" ng-repeat="elem in formElements">
 <div class="col-lg-12" ng-switch on="elem.eleType">
  <input ng-switch-when="text" type="text" id="{{elem.id}}" name="{{elem.id}}" class="{{elem.class}}" placeholder="{{elem.placeholder}}" popover-trigger="focus" popover="{{elem.popoverText}}">
  <input ng-switch-when="password" type="password" id="{{elem.id}}" name="{{elem.id}}" class="{{elem.class}}" placeholder="{{elem.placeholder}}" popover-trigger="focus"  popover="{{elem.popoverText}}">
  <input ng-switch-when="email" type="email" id="{{elem.id}}" name="{{elem.id}}" class="{{elem.class}}" placeholder="{{elem.placeholder}}" popover-trigger="focus"  popover="{{elem.popoverText}}">
 </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在这个例子中,你正在指导角脚本来比较elem.eleType使用ng-switch on在对输入标签的实际类型,即,文本,密码和电子邮件第二个div(使用相比ng-switch-when,只有该输入元素是创造一个条件匹配,其余的将被忽略.