gpt4 book ai didi

javascript - Angularjs 在指令链接函数中设置有效性

转载 作者:行者123 更新时间:2023-11-29 21:48:48 24 4
gpt4 key购买 nike

我的 angularjs 应用程序中有一个指令。我想将一个指令与多个模型绑定(bind)。但我只想设置一个模型的有效性,即数字这是我的代码。

<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
});


})
}
};
}])

在每次调用国家元素/代码元素或数字元素时,我只想设置数字模型的有效性。

最佳答案

我的解决方案是这样的。

<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 是因为它需要一些时间来初始化表单对象。希望能帮到你。

关于javascript - Angularjs 在指令链接函数中设置有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com