John Abraham
John Abraham

Reputation: 18791

On click How can I cycle through JSON one by one in AngularJS

Creating my first directive as an exercise in angular —making more or less a custom carousel to learn how directives work.

I've set up a Factory with some JSON data:

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

And an actors controller:

function actorsCtrl($scope, Actors) {
    $scope.actors = Actors;
  }

And am using ng-repeat to display the model data:

<div ng-controller="actorsCtrl">
  <div ng-repeat="actor in actors.detail">
    <p>{{actor.name}} </p>
  </div>
      <div ng-click="next-actor">Next Actor</div>
</div>

1) How do I only display the actor's name in the first index of my angular model actors.detail?

2) How do I properly create a click event that will fetch the following index and replace the previous actor.name

User flow:

Upvotes: 0

Views: 491

Answers (2)

hassassin
hassassin

Reputation: 5054

Since you only want the current user, the ng-repeat is not what you want to use, since that would be for each element in the data;

You would want to keep track of the index you are looking at in the scope, and increment that.

<div ng-controller="TestController">
    {{data[current].name}}
    <div ng-click="Next();"> NEXT! </div>
</div>

Where in the controller we also have these set up, where data is your actors:

$scope.current = 0;
$scope.Next = function() {
    $scope.current = ($scope.current + 1) % $scope.data.length;
};

Here's a fiddle where it's done.

Upvotes: 2

haki
haki

Reputation: 9759

I would change my serivce to return a single actor and maintain the index in the controller. something like this. This is an incomplete solution - you need to take care of cycle etc...

Upvotes: 1

Related Questions