簡體   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