Search code examples
javascripthtmljsonangularjsangularjs-ng-repeat

Angular - Get ng-repeat object


I need to get the current object out of an ng-repeat on ng-click, I can't use $index because I'm using orderBy and therefore it gives me the wrong index relative to the scope object. Idealy I want to be able to click on the object (thumbnail) and have $scope.activePerson gain all that objects values.

My data is structured as follows:

      [
        {
          'name': 'john'
        },
        {
          'name': 'toby'
        },
        {
          'name': 'sarah'
        }
      ]

This is very much simplified, my real objects have 30+ KV pairs and subobjects. There are 10 objects that I'm repeating from (in batches of 4).

My current HTML is:

.item.fourth(ng-repeat="person in people | orderBy:'-name' " ng-show="$index <= 3" nid="{{person.guid}}"

Thanks


Solution

  • You can just use orderBy and copy the current object from ng-repeat, see this plunkr. Relevant code:

    Controller

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.stuff = [
            {
              'name': 'john'
            },
            {
              'name': 'toby'
            },
            {
              'name': 'sarah'
            }
          ];
    
        $scope.setActivePerson = function (obj) {
          $scope.activePerson = obj;
        };
    });
    

    View

    <body ng-controller="MainCtrl">
        <div ng-repeat="thing in stuff | orderBy: 'name'">
          <input type="radio" ng-click="setActivePerson(thing)" />
          {{ thing.name }}
        </div>
        <br />
        <div ng-model="activePerson">Active: {{ activePerson.name }}</div>
      </body>