Search code examples
angularjsangularjs-scopeangularjs-orderby

AngularJS orderBy - how to reflect in parent scope?


How to reflect orderby in parent scope? Also I already tried to use prototype inheritance without success using sortorder.val as ng-model. An help?

<body ng-controller="parentCtrl">
   <table style="width:300px">
      <tr>
        <td>Name</td>
        <td>Age</td>      
      </tr>
      <tr ng-repeat="contact in contacts | orderBy:sortorder">
        <td>{{contact.name}}</td>     
        <td>{{contact.age}}</td>
      </tr>
  </table> 
  <br/>
<div ng-controller="childCtrl">
  Order By:
  <select ng-model="sortorder">
      <option selected value="name">Name</option>
      <option value="age">Age</option>
  </select>
</div>  
</body>

var app = angular.module('plunker', []);
app.controller('parentCtrl', ['$scope', function ($scope) {
$scope.sortorder = ['name'];
$scope.contacts = [
    {name: 'Alfred', age: 37},
    {name: 'Allan', age: 21},
    {name: 'Dimmi', age: 17},
    {name: 'Berta', age: 65},
    {name: 'Chris', age: 25},
    {name: 'Dora', age: 12}
];
app.controller('chilCtrl', function($scope) {

});
}]);

Plunk: http://plnkr.co/edit/bXGyund8v78Tal7lZ76O?p=preview


Solution

  • You have several errors in your code, that are signalled by the browser console:

    • the child controller is declared inside the parent controller: signalled in the browser console
    • it's declared as chilController instead of childController: signalled in the browser console
    • it uses an attribute of its scope instead of using an attribute of an object delared in the parent scope

    Here's a working plunkr: http://plnkr.co/edit/KhOpx4nwezXHRAZr3nOl?p=info

    var app = angular.module('plunker', []);
    app.controller('parentCtrl', ['$scope', function ($scope) {
      $scope.order = {
        sortorder: 'name'
      };
      $scope.contacts = [
        {name: 'Alfred', age: 37},
        {name: 'Allan', age: 21},
        {name: 'Dimmi', age: 17},
        {name: 'Berta', age: 65},
        {name: 'Chris', age: 25},
        {name: 'Dora', age: 12}
        ];
    }]);
    app.controller('childCtrl', function($scope) {
    
    });
    

    and in the view:

    <tr ng-repeat="contact in contacts | orderBy:order.sortorder">
    ...
    <select ng-model="order.sortorder">