2016-11-25 33 views
0

在我的應用程序中,我使用許多頁面的表單驗證。如果我想專注於無效輸入元素如何使用,而無需在每個元素的指令中設置true或false。如何使用ng.model在角度js中動態地聚焦輸入元素[不是首先]

<input type="text" ng-model="username" focus-me="isError"/> 

在controller.js:

if(scope.username == "") 
{ 
    scope.isError = true; 
} 

代替使用像上面的代碼,是否有任何方式使用NG-模型集中?

回答

0

你可以使用空白NG的消息也許這樣的事情,在你的控制器來觸發一個方法來設置焦點:

<form name="vm.foo"> 
    <input type="text" ng-model="username" id="fooUsername" /> 

    <ul 
    ng-messages="vm.foo.fooUsername.$error" 
    ng-if="vm.validFormItem(vm.foo.fooUsername)"> 
    <li ng-messages-include="some/validation/partial.html"> 
    </ul> 
</form> 

然後控制器內部的方法:

validFormItem(item) { 
    const returnValue = false; 
    // Do whatever checking you need in here to validate the form item 
    // to change returnValue; 

    // If it's false (not valid) then focus your form item here; 
    if (!returnValue) { 
    item.focus(); 
    } 

    return returnValue; 
} 

我還沒有測試過。

相關問題