0

I am using angular with ngDialog. I have in my view a list of users with an edit button which opens the user details in a ngDialog. Now when i save the data in my ngDialog I would like the list of users to be updated.

I thought to use a observer pattern for this. However the handler doesn't fire.

Here is my code:

User Controller

angular.module('myApp')
 .controller('UserController', function($scope, User){

    //this method gets fired when the dialog is saved
    $scope.update = function(user)
    {
        User.update(user);
        $scope.$broadcast('refresh-users');
        return true;
    }

});

UsersController:

angular.module('myApp')
 .controller('UsersController', function($scope, User, ngDialog){

    var loadUsers = function(users) {
        $scope.users = users;
    }

    var handleErrors = function(response) {
        console.error(response)
    }

    $scope.userPopup = function(id)
    {
        ngDialog.open(
            {
                template:'../partials/user.html',
                controller: 'UserController',
                data: {'id': id},
                scope: $scope
            });
    }
    $scope.$on('refresh-users', function handler(){
        console.log('handler');
        User.getAll()
            .then(loadUsers)
            .catch(handleErrors);
    });

});

How could I solve this?

sanders
  • 10,794
  • 27
  • 85
  • 127

2 Answers2

0

Use $rootScope instead of $scope as these two controllers are not using the same scope.

Rebornix
  • 5,272
  • 1
  • 23
  • 26
0

As has already been mentioned you want to use $rootScope for broadcasting if what you're trying to communicate is on another scope.

User Controller

angular.module('myApp')
 .controller('UserController', function($scope, $rootScope, User){

    //this method gets fired when the dialog is saved
    $scope.update = function(user)
    {
        User.update(user);
        $rootScope.$broadcast('refresh-users');
        return true;
    }

});

UsersController:

angular.module('myApp')
 .controller('UsersController', function($scope, $rootScope, User, ngDialog){

    var loadUsers = function(users) {
        $scope.users = users;
    }

    var handleErrors = function(response) {
        console.error(response)
    }

    $scope.userPopup = function(id)
    {
        ngDialog.open(
            {
                template:'../partials/user.html',
                controller: 'UserController',
                data: {'id': id},
                scope: $scope
            });
    }
    $rootScope.$on('refresh-users', function handler(){
        console.log('handler');
        User.getAll()
            .then(loadUsers)
            .catch(handleErrors);
    });

});
CodePrimate
  • 6,646
  • 13
  • 48
  • 86