John Abraham
John Abraham

Reputation: 18791

How to write a function using ng-click to move through indexes of an array

I would like to show a set of limited data. And have pagination interaction. How do I write a function: nextActor() to display the next actor[index] when user clicks on <button ng-click="nextActor()"></button>

I have a filter of limitTo: 1 on ng-repeat in hopes to only show 1 actor at a time

<div ng-controller="actorsCtrl">
  <div ng-repeat="actor in actors.detail | limitTo: 1">
    <p>{{actor.name}} </p>
    <button ng-click="nextActor()"></button>
  </div>
</div>

I have a service of data:

directiveApp.factory("Actors", function(){
    var Actors = {};
    Actors.detail = [
    {
      "name": "Russel Brand",
      "profession": "Actor",
      "yoga": [
        "Bikram",
        "Hatha",
        "Vinyasa"
      ]
    },
    {
      "name": "Aaron Bielefeldt",
      "profession": "Ambassador",
      "yoga": [
        "Bikram",
        "Vinyasa"
      ]
    },
    {
      "name": "Adrienne Hengels",
      "profession": "Ambassador",
      "yoga": [
        "Hatha",
        "Vinyasa"
      ]
    }
  ];
  return Actors;

});

And a very simple controller:

//creating a controller
function actorsCtrl($scope, Actors) {
   $scope.actors = Actors;
}

Upvotes: 0

Views: 180

Answers (2)

Sebastian G&#228;rtner
Sebastian G&#228;rtner

Reputation: 124

I wouldn't solve it this way.

Here are some ideas:

  • solve it via ng-view (oder ui-view -> Angular UI Router) instead of ng-repeat (if you don't know how: ask)
  • Solve it via ng-show/ng-hide and only show, hide the actual element. As ng-repeat has an $index (http://docs.angularjs.org/api/ng.directive:ngRepeat) you can build pagination with this. Just have a variable which is increased with every button click. Similar to Matts solution on this page (https://stackoverflow.com/a/20446461/1367646)
  • You may also write your own filter (maybe "offset")

Upvotes: 2

Matt Zeunert
Matt Zeunert

Reputation: 16561

As far as I know you can't pass a start index to limitTo, but you could do this without ng-repeat:

function actorsCtrl($scope, Actors) {
    $scope.actors = Actors;     
    $scope.index = 0;
    $scope.nextActor = function(){
        scope.index++;
    }
}

And do this in the html:

<p>{{actors.detail[index].name}} </p>
<button ng-click="nextActor()"></button>

Upvotes: 2

Related Questions