Peter Boomsma
Peter Boomsma

Reputation: 9806

Save specific data from array

I'm trying to find a way that allows me to save specific data from a array (or JSONP output).

Lets say I have this,

function Ctrl($scope) {
  $scope.movies = [
    {'title' : 'Star Wars', 'id' : '1'},
    {'title' : 'Inception', 'id' : '2'},
    {'title' : 'Inherent Vice', 'id' : '3'}
  ];
}

I display the results like this,

<div ng-controller="Ctrl">
  <div ng-repeat="movie in movies">
    {{ movie.id }} : {{ movie.title }} - <a href="#">Add Movie to watchlist</a>
  </div>
</div>

When you click on add movie to watchlist I want to store that movie title and id in a scope so I can use it later. How could I do that?

Here is the plunkr example http://plnkr.co/edit/tycuNmJy71Yr4SUia2e5?p=preview

Upvotes: 0

Views: 49

Answers (3)

Upalr
Upalr

Reputation: 2148

try this code::Demo

Html:

<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
    <script src="script.js"></script>
  </head>
  <body>    
    <div ng-controller="Ctrl">
        <div ng-repeat="movie in movies">
           {{ movie.id }} : {{ movie.title }} - <a href="#" ng-click="addMovie(movie)">Add Movie to watchlist</a>
       </div>      
  WishList: {{wishlist}}
   </div>   
 </body>
</html>

Controller:

function Ctrl($scope) {
  $scope.movies = [
    {'title' : 'Star Wars', 'id' : '1'},
    {'title' : 'Inception', 'id' : '2'},
    {'title' : 'Inherent Vice', 'id' : '3'}
  ];
  $scope.wishlist = [];

  $scope.addMovie = function(movie)
  {
    $scope.wishlist.push({id: movie.id, title: movie.title});
  }
}

Upvotes: 3

gandharv garg
gandharv garg

Reputation: 2181

Yes you can write a function in which you can pass the id of the selected item and store it in a scope variable. Like below :

  $scope.getDetails = function(id){
   alert(id);
   $scope.storedMovie = $scope.movies[id].title;
   alert($scope.storedMovie)
 }

UPDATED PLUNKER

Upvotes: 0

Guenter Guckelsberger
Guenter Guckelsberger

Reputation: 940

I added the function to your plnkr

demo

function Ctrl($scope) {
  $scope.movies = [
    {'title' : 'Star Wars', 'id' : '1'},
    {'title' : 'Inception', 'id' : '2'},
    {'title' : 'Inherent Vice', 'id' : '3'}
  ];
  
  $scope.select = function (movie) {
    //do your stuff here
    console.log(movie.title);
  }
}
<!doctype html>
<html ng-app>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js"></script>
    <script src="script.js"></script>

  </head>
  <body>

<div ng-controller="Ctrl">
  <div ng-repeat="movie in movies">
    {{ movie.id }} : {{ movie.title }} - <a href="#" ng-click="select(movie)">Add Movie to watchlist</a>
  </div>
</div>



  </body>
</html>

Upvotes: 0

Related Questions