眾所周知,在Angular中ngModel為動態雙向綁定,存在兩種方式。
例如,
方式一:
在html中,
<input type="text" ng-model="searchText" /><button ng-click="check(searchText)">Check!</button>{{ searchText }}
在controller中
$scope.check = function (searchText) { console.log(searchText);}
方式二:
引用stackoverflow的一句話,
“If you use ng-model, you have to have a dot in there.” Make your model point to an object.property and you'll be good to go.
在html中,
<input ng-model="formData.searchText"/><button ng-click="check()">Check!</button>
在controller中,
$scope.formData = {};$scope.check = function () { console.log($scope.formData.searchText.$modelValue);}
但是我們常常會對ngModel當中的值進行驗證,例如,
<input type="password" pattern="[0-9]*" placeholder="請輸入6位新密碼" ng-model="password.new_password" ng-blur="validateLength()">
<input type="password" ng-model="password.new_password" ng-keyup="compare(password)" name="repassword" ng-pattern="/^[0-9]{1,6}$/" />
發現ngModel當中的password.new_password不能實時綁定到controller中,原因為ngModel的值并沒有符合pattern的規則。若符合規則,則正常綁定傳遞。
以上這篇Angularjs之ngModel中的值驗證綁定方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答