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

时间:2015-05-10 20:59:40

标签: javascript angularjs

我的angularjs应用程序中有一个指令。我想绑定一个指令与多个模型。但是我想设置一个只有一个模型的有效性 这是我的代码。

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


            })
        }
    };
}])

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

1 个答案:

答案 0 :(得分:2)

我的解决方案就是这个。

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