1

new to AngularJS and trying to figure out how to pushing an array of objects data (not input strings) between controllers. Currently, my code pushes data into one controller('ChooseTabCtrl') but I want to push to another controller ('ListTabCtrl') so that the list displays on another page. I'm confused b/c most examples show only when a user enters a string of text. My project adds a fave by clicking a button. Any help would be appreciated.

1
  • 1
    There are several approaches, but i guess in your case the best approach would be to define a service where you persist your favourites. So you can use them from both controllers Commented Apr 19, 2016 at 20:55

1 Answer 1

1

You can create a service for this. Like:

.service('FavoritesService', function(){
    var favorites = [];

    this.getFavorites = function(){
        return favorites;
    };

    this.setFavorite = function(favorite){
        favorites.push(favorite);
    };
});

Set your favorites:

...
if (!$scope.myFaveItems.some(isAlreadyPresent)) {
    $scope.myFaveItems.unshift(item);
    FavoritesService.setFavorite(item);
}
...

Use it in your ListCtrl:

.controller('ListTabCtrl', function($scope, FavoritesService) {
    $scope.myFaveItems = FavoritesService.getFavorites();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the reply this is perfect!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.