简体   繁体   中英

Creating a custom form validator on an element directive in Angular?

I have a tags Angular element directive which operates very similarly to Stack Overflow's own 'tags' input field for questions here.

I want to validate that the ng-model attribute on the tag element is an array of at least one tag and less than ten tags. However, I don't want to create a separate directive to validate this, since I'll never need to validate the length of an array again. I want the logic to be self contained inside the element directive.

Here's what I've got so far:

angular.module("directives.tags", []).directive("tags", ["Tag", "$timeout", function(Tag, $timeout) {
return {
    require: 'ngModel',
    restrict: 'E',
    scope: {
        availableTags: '=',
        selectedTags: '=ngModel',
        placeholder: '@'
    },
    link: function($scope, element, attributes, ctrl) {

        // Snip

        ctrl.$validators.taglength = function(mv, vv) {
            return (mv.length > 0);
        }
    } 
}

And my directive is used like this:

<tags available-tags="data.tags" name="tags" ng-model="text.tags"></tags>
<span ng-show="writeForm.tags.$error.taglength">Invalid!</span>

But, my taglength validator is not working, or I am otherwise not binding it correctly. Any ideas?

In your template you need to refer to element name , not to variable in your controller's scope . And, in your directive's isolated scope, you could use plain ngModel .

For example:

<body ng-controller="Ctrl">
  Tags: {{ usedTags | json }}
  <ng-form name="writeForm">
    <tags name="tags" 
          ng-model="usedTags" 
          available-tags="availableTags">
    </tags>
    <span class="valid" 
          ng-show="writeForm.tags.$valid">
          Valid!
    </span>
    <span class="invalid" 
          ng-show="writeForm.tags.$error.taglength">
          Invalid!
    </span>
  </ng-form>

  <button type="button" 
          ng-click="changeModel()">
          Change
  </button>
</body>

angular.module("directives.tags", [])
  .controller('Ctrl', function($scope) {
    $scope.usedTags = [];
    $scope.availableTags = ['a','b'];

    $scope.changeModel = function() {
      $scope.usedTags = $scope.usedTags.length === 0 ? ['a'] : [];
    };
  })
  .directive("tags", function() {
    return {
      require: 'ngModel',
      restrict: 'E',
      scope: {
        ngModel: '=',
        availableTags: '='
      },
      link: function(scope, element, attributes, ctrl) {
        ctrl.$validators.taglength = function() {
          return scope.ngModel.length > 0;
        };
      }
    }; 
  });

Related plunker here http://plnkr.co/edit/SiC8wk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM