2

I have a controller that creates a list of movies. The controller does this by call a function inside a factory and then it puts the response in a scope which shows it in the view.

I also have a different controller in which I have a addMovie function. So users can add movies to their watchlist. My problem is that when a user adds a movie the view (or better the scope from the first controller) isn't updated and I have to reload the page to see the newly added movie.

What would be the best way to call the function from the first controller (that gets the data from the factory and places it in to the scope) when the addMovie function has been called?

addMovieController:

$scope.addMovie = function (movie)  {
    movieaddFactory.selectMovie(movie).then(function(response){
        movieaddFactory.addMovie(response);
        Notification.success(movie.title + ' has been added to your watchlist');
        $scope.movies = [];
        $scope.overlay = false;
        $scope.searchquery = ''
    });
};

getMovieController:

getmovieFactoryFN = function(){
    getmovieFactory.getMovies().then(function(response){
         $scope.mmovies = response;
    })
}

To clarify I want to call the getmovieFactoryFN inside the getMovieController when the addMovie function is called in the addMovieController.

1
  • I would use $broadcast to distribute your event to all controllers who is listen to. Commented Aug 14, 2016 at 10:14

1 Answer 1

1

Use $broadcast like:

$scope.addMovie = function (movie)  {
    movieaddFactory.selectMovie(movie).then(function(response){
        movieaddFactory.addMovie(response);
        Notification.success(movie.title + ' has been added to your watchlist');
        $scope.movies = [];
        $scope.overlay = false;
        $scope.searchquery = ''

        $rootScope.$broadcast('onAddMovieEvent', {/* some data */});
    });
};

in other controller:

$scope.$on('onAddMovieEvent', function (event, _data) {
     //  event.preventDefault(); // if you want to stop this event to spread over all your application
     getmovieFactoryFN();
 });
Sign up to request clarification or add additional context in comments.

1 Comment

Going for the easiest solution. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.