AngularJS嵌套表达式在ng-class

时间:2016-04-04 05:42:37

标签: angularjs

我怎样才能实现这样的目标:

ng-class="{ 'has-errors' : form_editProfile.password.$invalid && !form_editProfile.password.$pristine......

但是,在循环/ ng-repeats(动态表单和动态字段)中,如下所示:

 <div ng-repeat="(form, fields) in sections">
    <form name="form_{{form | alphanumeric}}" novalidate>
      <div ng-repeat="(name, field) in fields" ng-class="{ 'has-errors' : form_{form | alphanumeric}.{field}.$invalid && !form_{form | alphanumeric}.{field}.$pristine, 'no-errors' : form_{form | alphanumeric}.{field}.$valid">

......其中'alphanumeric'是我所拥有的过滤器,它将“Contact Info”转换为“ContactInfo”(有效的表单名称) - 例如。

基本的动态生成的表单/表单元素正在工作,我无法弄清楚如何在这种情况下使用嵌入式表达式使验证正常工作..

1 个答案:

答案 0 :(得分:2)

简单插值应该在这里工作,如下:

ng-class="{ 'has-errors' : form_{{form | alphanumeric}}.{{field}}.$invalid }"

这是一个快速演示,展示了如何在ng-class规则中插入表单名称和输入名称。

angular.module('myApp', [])
  .controller('MainCtrl', function($scope) {
    $scope.formName = 'TestForm';
    $scope.inputName = 'myInput';
  })
  .filter('lowercase', function() {
    return function(input) {
      return input.toLowerCase();
    }
  });
.red {
  color: red;
}
<section ng-app="myApp">
  <div ng-controller="MainCtrl">
    <form name="form_{{ formName | lowercase }}">
      <input type="text" name="{{ inputName }}" ng-model="inputValue" />
    </form>

    <span ng-class="{ 'red': form_{{formName | lowercase}}.{{inputName}}.$dirty }">
      This text will be red if the input is dirty
    </span>
  </div>
</section>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>