2017-03-21 23 views
0

我想列出項目,雙擊一個項目使其可編輯。目前,在編輯項目時,單擊外部(即blur)或通過鍵盤輸入提交新值。僅在滿足模式時才提交輸入值的許可

我希望只有當它不是空的或滿足模式(例如,文件名爲.)時才能提交新更改。我試過ng-required="true",它沒有工作。

有誰知道如何設置此限制?

JSBin

<!DOCTYPE html> 
<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> 
    <style> 
    input { 
     font-size: 20px; 
     border:none; 
     background-color:transparent; 
    } 
    </style> 
</head> 
<body ng-app="app" ng-controller="Ctrl"> 
    <table> 
    <tr ng-repeat="item in items"> 
     <td> 
     <input type="text" value="{{item.name}}" ng-blur='eEditable = -1' ng-readonly='$index !== eEditable' ng-dblclick="eEditable = $index" ng-keypress="keypress($event)" ng-required="true"/> 
     </td> 
    </tr> 
    </table> 
    <script> 
    var app = angular.module('app', []); 
    app.controller('Ctrl', ['$scope', function ($scope) { 
     $scope.items = [{ name: "item #1" }, { name: "item #2" }, { name: "item #3" }]; 
     $scope.eEditable = -1; 
     $scope.keypress = function ($event) { 
     if ($event.keyCode === 13) 
      $event.target.blur() 
     } 
    }]) 
    </script> 
</body> 
</html> 

編輯1:現有的答案,建議使用form,但我不希望使用formsubmit按鈕。

一種解決方案是驗證myBlur函數中的新值:如果模式不滿足,我們可以將焦點設置回輸入字段並讓用戶再次修改該值。這是另一個JSBin

有誰知道如何將的焦點設回輸入欄

回答

0

有人知道如何將焦點設置回輸入欄位嗎?

如果您在ngKeypress事件中驗證輸入,則可以使用$事件。 如果驗證失敗,請將焦點重新設置爲輸入

angular.element($event.currentTarget).focus(); 
+0

確實,在'ngKeypress'我們可以做到這一點...但我們怎麼能在鼠標模糊的同時做到這一點? – SoftTimur

+1

對於模糊,你可以使用NgBlur事件,它也在$ event中提供事件https://docs.angularjs.org/api/ng/directive/ngBlur –

+0

@SoftTimur看到我對模糊的評論 –

0

使用NG模式使用正則表達式

<input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /> 

我發現這個網站有幫助決策的正則表達式http://regexr.com/

+0

您確定它對我的示例有效嗎? – SoftTimur

+0

是的,但Bens的答案更詳細,你需要將輸入放在表單中,然後ng-required應該可以工作。 – joegod86

0

你可以阻止提交使用<form>ng-submitng-required,並ng-pattern指令:

<form name="myForm" ng-submit="submitClicked($event, myForm)"> 
    <input type="text" ng-required="true" ng-pattern="/.)/"> 
    <input type="submit"> 
</form> 

$scope.submitClicked = function($event, form) { 
    if (!form.$valid) { 
      $event.preventDefault(); 
    } 
} 
+0

但問題是我不想在我的列表中添加'form'或'submit'按鈕...... – SoftTimur

相關問題