繁体   English   中英

如何使用angular.js禁用输入框

[英]How to disable an input box using angular.js

我正在使用此字段进行编辑视图和创建视图

<input data-ng-model="userInf.username"  class="span12 editEmail" type="text"  placeholder="me@example.com"  pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required />

在控制器中我有这个代码来禁用输入元素:

function($rootScope, $scope, $location, userService)
{

//etc 
    $(".editEmail" ).attr("disabled", disable);  // no idea how to do in angular
}

请帮忙。

使用ng-disabled或带有ng-class的特殊CSS

<input data-ng-model="userInf.username"  
       class="span12 editEmail" 
       type="text"  
       placeholder="me@example.com"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{expression or condition}"
/>

您需要使用ng-disabled指令

<input data-ng-model="userInf.username" 
       class="span12 editEmail" 
       type="text" 
       placeholder="me@example.com" 
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="<expression to disable>" />

我为此创建了一个指令(角度稳定1.0.8)

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});

您的标记应该包含一个名为ng-disabled的附加属性,其值应该是一个条件或表达式,它将被评估为true或false。

    <input data-ng-model="userInf.username"  class="span12 editEmail" 
       type="text"  placeholder="me@example.com"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{condition or expression}"
/>

在控制器中,您可能会有一些代码会影响ng-disabled指令的值。

<input type="text" input-disabled="editableInput" />
<button ng-click="editableInput = !editableInput">enable/disable</button>

app.controller("myController", function(){
  $scope.editableInput = false;
});

app.directive("inputDisabled", function(){
  return function(scope, element, attrs){
    scope.$watch(attrs.inputDisabled, function(val){
      if(val)
        element.removeAttr("disabled");
      else
        element.attr("disabled", "disabled");
    });
  }
});
<input data-ng-model="userInf.username"  class="span12 editEmail" type="text"  placeholder="me@example.com"  pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" required ng-disabled="true"/>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM