【问题标题】:angular ng-repeat expressions as variables角度 ng-repeat 表达式作为变量
【发布时间】:2013-07-31 13:06:46
【问题描述】:

我正在尝试做这样的事情:

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

但因为ng-repeat 逻辑处于指令的编译状态,它会将{{myRepeatExpression}} 视为普通字符串而不是变量。这显然是行不通的。

有什么解决方法吗?

【问题讨论】:

    标签: angularjs expression directive ng-repeat


    【解决方案1】:

    您只能使用和表达 ng-repeat 而不是 interpolated 值。 现在,为了创建动态可重复列表,您可以尝试以下任一方法:

    1. 使用在 ng-repeat 中动态返回列表的函数 - 这可能会更昂贵,因为 angular 需要先调用该函数,然后在执行 $digest 循环时确定集合是否已更改
    2. $watch 用于触发列表更改的范围内的特定变量 - 可能更有效,但如果您的动态列表依赖于多个变量,它可能会变得更冗长,并可能导致忘记添加的潜在错误需要新变量时的新$watch

    Demo 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>
    

    【讨论】:

      【解决方案2】:

      ng-repeat 只接受 row in rows 中的专有表达式语法,但 rows 可以是控制器中的函数或承诺。但是,您需要密切关注性能,因为 ng-repeat 不能很好地处理经常变化的事物(可怕的最大 10 次迭代错误)。

      【讨论】:

      • 谢谢,我知道语法但是如果你想将表达式存储在变量中怎么办?
      • 如果它只是一个未评估的 (DOM-)String(通过 $parse 或 $scope.$eval),那么就没有办法这样做。
      【解决方案3】:

      您不能将 ng-repeat 与应该直接表示表达式的字符串/变量一起使用,但您可以创建插值/解析该值并将其传递给 ng-repeat 参数并重新编译元素的指令。

      app.directive('ngVarRepeat',function($compile){
        return {
          priority:1001, //must be higher than 1000 (priority of ng-repeat)
          compile:function($elm,$attrs){
      
            var expression = $attrs.ngVarRepeat;
            $elm.removeAttr('ng-var-repeat'); // remove attribute so we can recompile it later
      
            return function(scope,elm,attrs){
              $elm.attr('ng-repeat',scope.$eval(expression));
              $compile($elm)(scope);
            }
          }
        }
      })
      

      看看这个 plunker:demo plunker from accepted answer

      另外请注意,这种方法会在嵌套的 ng-repeats 中引起麻烦。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-13
        • 1970-01-01
        • 2015-01-15
        相关资源
        最近更新 更多