AngularJS ngMessages无法绑定到$ index表达式 [英] AngularJS ngMessages can't bind to $index expression

查看:54
本文介绍了AngularJS ngMessages无法绑定到$ index表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Angular表单,需要在 ngRepeat 中包含可重复的表单元素。

I am building an Angular form that needs repeatable form elements inside an ngRepeat.

<form name="form">
    <div ng-repeat="x in [1,2,3,4]">
      <input name="something_{{$index}}" ng-model="hi" required>
      <div ng-messages="form.something_{{$index}}.$error">
        <ng-message="required">This is required</ng-message>
      </div>
    </div>
    <pre>{{form | json: 4}}</pre>
  </form>

Angular现在支持动态声明的输入名称所以您不必执行以下操作:

Angular now supports dynamically declared input names so that you don't have to do something like:

<div ng-repeat="x in [1,2,3,4] ng-form="repeated-form"></div>

您可以在 ngRepeat 中使用 {{$ index}} 来动态声明项目。但这似乎不是使用 ngMessages ,当我尝试将索引绑定到它时抛出错误。

And you can use {{$index}} inside the ngRepeat to declare items dynamically. But this doesn't seem to work with ngMessages, which throws an error when I try to bind the index into it.

即:

<div ng-messages="form.something_{{$index}}.$error">

抛出这个:

Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 16 of the expression [form.something_{{$index}}.$error] starting at [{{$index}}.$error].

我们如何动态声明表单上的哪个属性要监视,如果ng-消息不能用ch用{{$ index}}声明的表单值?

How can we dynamically declare which property on the form to watch, if ng-messages can't watch the form value that is declared with its {{$index}}?

PLNKR: http://plnkr.co/edit/4oOasbtffTgKqmxcppUG?p=preview (检查控制台)

PLNKR: http://plnkr.co/edit/4oOasbtffTgKqmxcppUG?p=preview (check console)

推荐答案

ng-messages="form['something_' + $index].$error"

应该有效。我通常不会将{{}}放在任何ng指令中,因为大多数ng指令都以优先级0执行(包括{{}}指令ngBind)。此外,ng指令都在其参数上使用$ evaluate,因此默认情况下它们会查看范围中的变量值。

Should work. I generally wouldn't put {{ }} in any of the ng directives because most of the ng directives execute with priority level 0 (including the {{ }} directive, ngBind). Also, the ng directives all use $evaluate on their argument, so they look at variable values in the scope by default.

同一元素上多个指令的优先级0意味着Angular无法保证首先应用哪个指令。因此,通常最好避免一起使用ngDirectives,因为行为可能会有所不同。 ngIf是一个例外,因为它以优先级600执行(这就是为什么不针对当前不在DOM中的ng-if元素评估指令的原因。)

Priority 0 for multiple directives on the same element means that Angular can't guarantee which directive will be applied first. Because of that, it is generally best to avoid using ngDirectives together as behavior can vary. ngIf is an exception as it executes with priority 600 (which is why directives aren't evaluated for an ng-if element not currently in the DOM no matter what).

这篇关于AngularJS ngMessages无法绑定到$ index表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆