角NG重复前pressions作为变量 [英] angular ng-repeat expressions as variables

查看:159
本文介绍了角NG重复前pressions作为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做这样的事情:

<ul>
    <li ng-repeat="{{myRepeatExpression}}">{{row.name}}</li>
</ul>

但因为 NG-重复逻辑在该指令的编译状态,它对待 {{myRepeatEx pression}} 作为一个普通的字符串,而不是一个变量。它不工作,效果显着。

But because the ng-repeat logic is in the compile state of the directive it treats the {{myRepeatExpression}} as a normal string instead of a variable. Which doesn't work, obviously.

是否有任何解决方法吗?

Is there any workaround for that?

推荐答案

您只能使用和前pression与 NG-重复而不是插入值。
现在,为了创建一个动态重复列表,你可以尝试之一:

You can only use and expression with ng-repeat and not an interpolated value. Now in order to create a dynamic repeatable list you can try either:


  1. 使用动态返回在 NG-重复列表中的功能 - 的这可能是更昂贵的,因为角度的需求,首先调用的函数,然后确定做一个 $消化周期时集合发生更改

  2. $观看为触发列表的变化范围的特定变量 - 的可能更为高效,但如果你的动态列表取决于多个变量它可以得到更详细的,可从忘了加导致潜在的bug一个新的 $观看时,需要一个新的变量

  1. using a function that returns the list dynamically in the ng-repeat - this is potentially more expensive since angular needs to call the function first then determine if the collection has changed when doing a $digest cycle
  2. $watch for a particular variable on the scope that trigger a change of the list - potentially more efficient but if your dynamic list depends on more than one variable it can get more verbose and can lead to potential bugs from forgetting to add a new $watch when a new variable is required

演示plunker

JS:

app.controller('MainCtrl', function($scope) {
  var values1 = [{name:'First'}, {name:'Second'}];
  var values2 = [{name:'Third'}, {name:'Fourth'}, {name:'Fifth'}];

  //1. function way
  $scope.getValues = function(id) {
    if(id === 1) {
      return values1;
    }
    if(id === 2) {
      return values2;
    }
  }

  //2. watch way
  $scope.values = undefined;
  $scope.$watch('id', function(newVal) {
    $scope.values = $scope.getValues(newVal);
  });
});

HTML:

<!-- Here we pass the required value directly to the function -->
<!-- this is not mandatory as you can use other scope variables and/or private variables -->
<ul>
  <li ng-repeat="v in getValues(id)">{{v.name}}</li>
</ul>
<!-- Nothing special here, plain old ng-repeat -->
<ul>
  <li ng-repeat="v in values">{{v.name}}</li>
</ul>

这篇关于角NG重复前pressions作为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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