1
 <FORM>
 <DIV class="outer-class">
      <INPUT class="toValidate" type = "text"/>
      <INPUT class="somethingElse" type= "text"/>
      <INPUT class="toValidate" type ="text"/>
 </DIV>
 <DIV class="outer-class">
      <INPUT class="toValidate" type = "text"/>
      <INPUT class="somethingElse" type= "text"/>
      <INPUT class="toValidate" type ="text"/>
 </DIV>
 <INPUT type="submit"/>
 </FORM>

My question is: How do I ensure that for the form to be valid, the nested toValidates have a unique value but only within the same outer div? I am guessing this logic should go in an OuterClassDirective, but I can't seem to figure out what the logic should look like?

Any advice would be appreciated.

Thanks!

4

2 回答 2

1

The 'tabs' and 'pane' directives on the Angular home page solve a similar issue -- the child 'pane' directives need to communicate with the parent 'tabs' directive.

Define a controller on the outerclass directive, and then define a method on the controller (use this not $scope). Then require: '^outerclass' in the toValidate directive. In the toValidate link function, you can $watch for value changes and call the method on the outerclass controller to pass the value up. Do the validation in the outerclass directive.

See also 'this' vs $scope in AngularJS controllers.

于 2013-01-08T21:37:50.347 回答
1

What about this. Your outerClassDirective should have a controller, which will store used values in an array. It will transclude the input fields in its body. Your toValidate directive requires outerClassDirective and adds the model value to the array, making it invalid if exists.

Here is a try (untested):

app.directive('outerClass', function() {
   var values = [];
   var valid = true;
   return {
      template: '<div ng-transclude></div>',
      transclude: true,
      replace: true,
      require: 'ngModel',
      controller: function() {
         this.addValue: function(value) {
            valid = values.indexOf(value) > -1;
            values.push(value);
         };
      },
      link: function(scope, elm, attrs, ctrl) {
         ctrl.$setValidity('toValidate', valid)
      }
   };
});

app.directive('toValidate', function() {
   return {
        require: '^outerClass',
        link: function(scope, elm, attrs, ctrl) {
           ctrl.addValue(attrs.value);
        } 
      }
   };
});
于 2013-01-08T21:53:56.743 回答