简体   繁体   English

在Angular指令中访问$ error

[英]Access $error in Angular directive

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. 现在我想访问指令中表单IN的$error变量。 Something like form.{{name}}.$error.number . 类似于form.{{name}}.$error.number

Is there a way to do this? 有没有办法做到这一点?

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. 看看https://docs.angularjs.org/guide/directive ,更具体地说,关于隔离范围的部分可能对您有所帮助。

Maybe it's enough to get the $error of the specific ngModelController ? 也许它足以获得特定ngModelController$error

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 http://plnkr.co/edit/wzuWT1lVevCLHkLLBIAT?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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