我应该如何在ng-repeat中连接变量和字符串

时间:2017-05-17 06:32:31

标签: angularjs

我有一个parents['a','b','c']的列表, 和3个孩子名单:

$ctrl.aChildren = ['aa','aaa']
$ctrl.bChildren = ['bb','bbb']
$ctrl.cChildren = ['cc','ccc']

我想使用外部<li>

中的变量parent在内部<li>中访问这3个变量
<li ng-repeat="parent in $ctrl.parents">
    ....
    <ul>
        <li ng-repeat="child in $ctrl[{{parent}} + 'Children']">
        </li>
    </ul>
    ...
</li>

我说错误

  

'{'是意料之外的

由于

2 个答案:

答案 0 :(得分:1)

你不需要放{{}}。它应该是这样的

 <li ng-repeat="parent in $ctrl.parents">
   {{parent}}
 <ul>
     <li ng-repeat="child in $ctrl[parent + 'Children']">
       {{child}}
     </li>
 </ul>

&#13;
&#13;
var app = angular.module('anApp', []);
app.controller('ctrl', function($scope) {
  var $ctrl = this;
  $ctrl.parents = ['a', 'b', 'c'];
  $ctrl.aChildren = ['aa', 'aaa']
  $ctrl.bChildren = ['bb', 'bbb']
  $ctrl.cChildren = ['cc', 'ccc']
})
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>

<div ng-app="anApp" ng-controller="ctrl as $ctrl">
  <li ng-repeat="parent in $ctrl.parents">
    {{parent}}
    <ul>
      <li ng-repeat="child in $ctrl[parent + 'Children']">
        {{child}}
      </li>
    </ul>
  </li>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您无需在ng-repeat指令中添加{{}}。替换以下代码

<li ng-repeat="child in $ctrl[{{parent}} + 'Children']">

<li ng-repeat="child in $ctrl[parent + 'Children']">