尽管数据是一个数组,但是ng-repeat上的命令仍无法正常工作

时间:2017-01-05 02:05:05

标签: html angularjs angularjs-ng-repeat angularjs-orderby

在html中

<div ng-controller="homeCtrl as home">
<a class="list-group-item" ng-repeat="e in home.events | orderBy:'popularity'"> {{ e.name }}</a>
</div>

在控制器中

var vm = this;

vm.events = [{
            "name": "one",
            "popularity": 1
        }, {
            "name": "four",
            "popularity": 4
        }, {
            "name": "two",
            "popularity": 2
        }];

我收到此错误https://docs.angularjs.org/error/orderBy/notarray?p0=%7B%7D

3 个答案:

答案 0 :(得分:1)

确保您在视图中使用 Controller As 语法

 <div ng-controller="ListCtrl as home">

<强>样本

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

app.controller("ListCtrl", ["$scope",
  function($scope) {
    var vm = this;

    vm.events = [{
      "name": "one",
      "popularity": 1
    }, {
      "name": "four",
      "popularity": 4
    }, {
      "name": "two",
      "popularity": 2
    }];
  }

]);
<!DOCTYPE html>
<html>
<head>
  <script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>
<body ng-app='app'>
  <div ng-controller="ListCtrl as home">
  <a class="list-group-item" ng-repeat="e in home.events | orderBy:'popularity'"> 
  {{ e.name }}</a>
  </div>
</body>
</html>

答案 1 :(得分:0)

您可能缺少controllerAs语法:

看看这个小提琴:

http://jsfiddle.net/adel_mehrban/ogrvmx61/1/

答案 2 :(得分:0)

我的问题是我有

vm.events = {};
在调用函数之前

我将其更正为

vm.events = [];

并修复了它。

感谢您的回答。对不起,我的问题并没有我的所有代码:/