2015-05-10 5 views
2

У меня есть директива в моем приложении 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 
       }); 


      }) 
     } 
    }; 
}]) 

В каждом элементе элемента/элемента элемента или элемента элемента страны я хочу установить действительность только модели числа.

+0

Вы нашли ответ? –

+0

@SergeyPanfilov Я написал свое решение. Пожалуйста, сообщите мне, если вы найдете лучшее решение. – 9me

+0

Мое дело немного другое, так или иначе это решение для моего дела: http://stackoverflow.com/a/36722197/930170 –

ответ

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

$ таймаут используется потому, что его принимает некоторое время для инициализации объекта формы. Надеюсь, я помогу тебе.

Смежные вопросы