【问题标题】:ng-repeat over a non-array/object / dealing with arrays and non-arrays the same way对非数组/对象进行 ng-repeat / 以相同方式处理数组和非数组
【发布时间】:2014-09-23 16:58:51
【问题描述】:

通常我想以相同的方式处理数组和单个对象。例如,我有一个对象的属性,它可以是数组或字符串(查看scale 属性):

[
 {
    "name": "Experiment type14",
    "id": "00000000014",
    "scale": ["Whole Brain", "Cell"],

 },
 {
    "name": "Experiment type15",
    "id": "00000000015",
    "scale": "Cell",
 }
]

我想要在这里展示我的scale

<span ng-repeat="scale in experimentType.scale">
 <!--some decoration here--> {{scale}}
</span>

当然这不适用于单个字符串值。有什么优雅的方法不用担心我是在处理字符串还是数组?

【问题讨论】:

  • 我个人认为过滤器是处理这个问题的最佳方式。一种统一数据的方法,因此您的视图只需担心一种格式。
  • 我也在考虑这样的事情。我喜欢它在 jquery 中的完成方式:您只需将内容包装在 $() 中,而无需担心对象/数组。

标签: javascript arrays angularjs angularjs-ng-repeat


【解决方案1】:

您可以创建自定义过滤器,请参见下文

var app = angular.module("app", []);

function MainCtrl() {
  this.message = "Welcome";
  this.data = [{
    "id": "00000000014",
    "name": "Experiment type14",        
    "scale": ["Whole Brain", "Cell"],
   },{
    "id": "00000000015",
    "name": "Experiment type15",
    "scale": "Cell",
   }];  
}

function toArray() {
  return  function(input) {
    console.log(input);
    if (angular.isArray(input)) {
      return input;
    } else {
      return [input];
    }
  };
}

angular.module("app").controller("MainCtrl", MainCtrl);
angular.module("app").filter('toArray', toArray);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
  <div ng-controller="MainCtrl as vm">
    <div class="container">
       <h3>{{ vm.message }}</h3>
      <div ng-repeat="item in vm.data">
        <p>{{ item.name }}</p>
        <ul>
          <li ng-repeat="scale in item.scale | toArray">{{ scale }}</li>
        </ul>
      </div>
    </div>
  </div>
</body>

【讨论】:

    【解决方案2】:

    这是我最好的尝试。我只是在范围内实现以下功能:

    $scope.toArrayIfNot = function (input) {
            if (Object.prototype.toString.call(input) === '[object Array]') {
                return input;
            }
            return [input];
        };
    

    然后我就这样使用它:

    <span ng-repeat="scale in toArrayIfNot(experimentType.scale)">
     <!--some decoration here--> {{scale}}
    </span>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-12
      • 1970-01-01
      • 2013-06-24
      相关资源
      最近更新 更多