4

I have an input wrapped in a directive with a dynamic name like this:

<input class="input-field" name="{{name}}" type="number" ... />

Now I want to access the $error variable of the form IN the directive. Something like form.{{name}}.$error.number.

Is there a way to do this?

ndsmyter
  • 6,535
  • 3
  • 22
  • 37
christof
  • 133
  • 1
  • 8

2 Answers2

0

If you want to access the form (that is on the parent scope) you have to pass the form to your directive. To do this, you have to specify that you want two way binding (using =) when you define your directive.

Have a look at https://docs.angularjs.org/guide/directive, more specifically the part about isolating the scope can probably help you.

ndsmyter
  • 6,535
  • 3
  • 22
  • 37
  • That I know. But I does not know how I can access the specific field on the form dynamically. The field's name is stored in a variable... – christof Jul 03 '15 at 07:47
  • Ah, I misunderstood the question then. Have you tried `form[name].$error.number` ? – ndsmyter Jul 03 '15 at 09:34
0

Maybe it's enough to get the $error of the specific ngModelController?

return {
  template: '<input ng-model="value" type="number" /><span ng-bind="error | json"></span>',
  scope : {},
  link: function(scope, elem, attr) {
    scope.error = elem.find('input').controller('ngModel').$error;
  }
}

http://plnkr.co/edit/wzuWT1lVevCLHkLLBIAT?p=preview

hansmaad
  • 18,417
  • 9
  • 53
  • 94