2015-06-26 88 views
0

我正在使用指令來構建一個自定義驗證器,它工作正常。但是,它只被稱爲一次!如果我的「roleItems」被更新,這個指令不會再被調用!每次更新「roleItems」時如何調用它?角度指令只被調用一次

這裏是標記。而「非空」是我的指令。

<form name="projectEditor">  
    <ul name="roles" ng-model="project.roleItems" not-empty> 
     <li ng-repeat="role in project.roleItems"><span>{{role.label}}</span> </li> 
     <span ng-show="projectEditor.roles.$error.notEmpty">At least one role!</span> 
     </ul> 
    </form> 

這是我的指令。它應該檢查ng-model「roleItems」是否爲空。驗證的

angular.module("myApp", []). 
    directive('notEmpty', function() { 
     return { 
      require: 'ngModel', 
      link: function (scope, elm, attrs, ctrl) { 

       ctrl.$validators.notEmpty = function (modelValue, viewValue) { 


        if(!modelValue.length){ 
         return false; 
        } 

        return true; 
       }; 

      } 
     }; 
    }); 
+1

你打算在ul上做什麼? ng-model用於對輸入等組件進行雙向數據綁定,其中用戶可以輸入存儲在模型變量中的值。 ul不能這樣做。這沒有意義。只需刪除此指令並使用

回答

0

主要目的是驗證用戶輸入或模型的變化ngModel價值,所以應該USET到複選框/ textara /輸入等一切你不能驗證NG-模型。 Angular非常聰明,知道ng模型沒有敏感,所以他只是忽略它。

我想只更改錯誤消息,您可以通過.length屬性檢查它。如果你想使整個表單無效,我建議你做自定義指令,把它放在,然後在這個指令驗證器檢查scope.number.length> 0

基本上只是調整你的指令代碼輸入元素和隱藏它....通過CSS或類型=隱藏,但不要讓ngModel =「價值」它沒有意義,因爲ng-model期待可綁定和覆蓋的值,但project.roleItems不可綁定!所以把ng-model =「dummyModel」和實際物品放到另一個參數中...

<input type="hidden" ng-model="dummyIgnoredModel" number="project.roleItems" check-empty> 


angular.module("myApp", []). 
    directive('checkEmpty', function() { 
     return { 
      require: 'ngModel', 
      link: function (scope, elm, attrs, ctrl) { 

       ctrl.$validators.push(function (modelValue, viewValue) { 


        if(!scope.number.length){ 
         return false; 
        } 

        return true; 
       }); 
      //now we must "touch" ngModel 
       scope.$watch(function() 
       { 
        return scope.number 
       }, function() 
       { 
        ctrl.$setViewValue(scope.number.length); 
       }); 
      } 
     }; 
    });