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?

2 Answers 2

0

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

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

});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.