orderBy on ng-repeat is not working despite data being an array

83 views Asked by At

In html

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

In the controller

var vm = this;

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

I get this error https://docs.angularjs.org/error/orderBy/notarray?p0=%7B%7D

3

There are 3 answers

0
bobsim21 On

My problem was that I had

vm.events = {};

before the function was called and I corrected it to

vm.events = [];

and it fixed it.

Thanks for the answers. Sorry my question didnt quite have all my code :/

1
Sajeetharan On

Make sure you are using Controller As syntax in view

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

DEMO

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="[email protected]" 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>

0
Yaser On

You are probably missing the controllerAs syntax:

Take a look at this fiddle:

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