转换ng-repeater多级值

时间:2016-04-05 08:51:25

标签: angularjs angularjs-ng-repeat ng-repeat

我正在尝试解决两个问题(即使其中一个问题不是真正的问题)。

我必须通过两级对象迭代,看起来非常像这样:

{"id": "1","details": [{"name": "Name 1","surname": "Surname 1"}]},
{"id": "2","details": [{"name": "Name 2","surname": "Surname 2"}]},
{"id": "3","details": [{"name": "Name 3","surname": "Surname 3"}]},
{"id": "4","details": [{"name": "Name 4","surname": "Surname 4"}]}

我还需要使用ID作为参数转换打印值:

$scope.convert = function (id){
  switch (id) {
    case "1":
       $scope.role = "role 1"
    break;
    case "2":
       $scope.role = "role 2"
    break;
    case "3":
       $scope.role = "role 3"
    break;
    case "4":
       $scope.role = "role 4"
    break;
  }
}

现在,在html中,这就是我目前所拥有的:

<h3>Works - with nested repeaters</h3>
<ul ng-repeat="i in items" ng-click="convert('{{i.id}}')">
   <ul ng-repeat="a in i.details">
      {{a.name}}
   </ul>
</ul>  
<br/>
{{role}}

以下是问题:

  • 我知道在另一个ng-repeat内使用ng-repeat可以胜任这项工作,但我认为这不是处理此类情况的最佳方式。我也尝试了ng-repeat-start/end,但我无法弄清楚是怎么回事,因为我总是得到一个错误,说即使它在那里也没有找到结束。

  • 如果我点击名称来调用转换函数,它会起作用,但是如果我尝试将函数调用到转发器中,就像这个{{ convert ('{{a.id}}') }}一样,它会失败。总而言之,我需要的是能够将转换后的字符串直接显示到转发器中而不是ID(不幸的是,我无法更改json文件)。

以上是我上面描述的内容:http://codepen.io/anon/pen/YqXBqN?editors=1010

2 个答案:

答案 0 :(得分:2)

您需要更改转换方法,如 -

 $scope.convert = function (id){
     switch (id) {
        case "1":
         return "role 1"
        break;
        case "2":
         return "role 2"
        break;
        case "3":
         return "role 3"
        break;
        case "4":
         return "role 4"
        break;
      }

    }

然后更新你的html as-

<ul ng-repeat="i in items" ng-click="convert('{{i.id}}')">
      <ul ng-repeat="a in i.details">
        {{i.id}} - {{a.name}}- {{convert(i.id)}}

      </ul>
    </ul>  

它的输出将是 -

1- Name 1 -role 1
2- Name 2 -role 2
3- Name 3 -role 3
4- Name 4 -role 4

答案 1 :(得分:1)

语法错误 ng-click="convert('{{i.id}}')"应转换为ng-click="convert(i.id)"

而不是声明role变量值 将attr添加到模型中,因为id很重要

$scope.addRole = function (model){
    var id = '' + model.id;
    switch (id) {
        case "1":
            model.role = 'role 1';
            break;
        case "2":
            model.role = 'role 2';
            break;
        case "3":
            model.role = 'role 3';
            break;
        case "4":
            model.role = 'role 4';
            break;
    }
}

HTML

<ul ng-repeat="i in items">
    {{addRole(i)}}
    {{i.id}} - {{i.role}}
</ul>