本文介绍了Angularjs在指令链接函数中设置有效性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的angularjs应用程序中有一个指令。我想绑定一个指令与多个模型。但是我想设置只有一个模型的有效性,这个数字是
这里是我的代码。
I have a directive in my angularjs app. I want to bind one directive with more then one models. But I want to set validity of only one model which is numberhere is my code.
<form name="userForm">
<select unique-phone name="country" class="form-control" ng-model="newUser.country" ng-options="country.name for country in userdata.country"></select><!-- this drop down is for prefix like +971 -->
<select unique-phone name="code" ng-model="newUser.code" ng-options="mobile for mobile in userdata.mobile_codes" required></select>
<input unique-phone name="number" ng-model="newUser.number" type="number" ng-pattern="/^[0-9]+$/" />
</form>
//Javascript
.directive('uniquePhone', ['$http', function ($http) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModel) {
scope.$watch( function(){ return element.val(); }, function(value){
if(scope.newUser.number === undefined || scope.newUser.country === undefined || scope.newUser.code === undefined || scope.newUser.number.toString().length != 7) {ngModel.$loading = false; return;}
ngModel.$loading = true;
var objFInal = scope.newUser.country.code + scope.newUser.code + scope.newUser.number;
$http.get("/api/checknumber/" + objFInal).success(function(data) {
ngModel.$loading = false;
ngModel.$setValidity('taken', JSON.parse(data));// I just want to set validity of number model on each case...
// like userForm.number.$setValidity('taken', true) instead of ngModel.$setValidity
});
})
}
};
}])
在每次调用时,如国家元素/代码元素或我想要的数字元素仅设置数字模型的有效性。
On each call like country element / code element or number element I want to set validity of number model only.
推荐答案
我的解决方案就是这样。
My solution is this.
<form name="form" novalidate ng-submit="submit(form)">
<div ng-show="form.pfx.$error.invalid">Prefix is invalid</div>
<div ng-show="form.code.$error.invalid">Code is invalid</div>
<div ng-show="form.number.$error.invalid">Number is invalid</div>
<select phone frm="form" ng-model="phm.pfx" name="pfx" required ><option>971</option></select>
<select phone frm="form" ng-model="phm.code" name="code"></select>
<input phone frm="form" type="text" ng-model="phm.number" name="number" />
<input type="submit" value="OK" />
</form>
指令就在这里
app.directive('phone', ['$timeout', function($timeout){
return {
scope: {frm:"="},
require: 'ngModel',
link: function($scope, iElm, iAttrs, controller) {
controller.$error.invalid = true;// this will be current element which is calling this link function
$timeout(function(){
$scope.frm.pfx.$error.invalid = true;
$scope.frm.code.$error.invalid = true;
$scope.frm.number.$error.invalid = true;
});
}
};
}]);
使用$ timeout因为它需要一些时间来初始化表单对象。我希望我会帮助你。
$timeout used because its taking some time to initialize form object. I hope i will help you.
这篇关于Angularjs在指令链接函数中设置有效性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!