Peter Boomsma Peter Boomsma - 3 months ago 9
AngularJS Question

Call method from different controller with Angular

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.

Answer

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();
 });
Comments