2

I have two angular services that need to share models (a list of messages and an individual message), which they get from a call to our API. The service is as follows:

angular.module('CmServices', ['ngResource'])
.factory('Messages', function ($resource, $routeParams, $rootScope) { 

    var data = {};

    data.rest = $resource(url, {}, {
            query: {method:'GET', params: params},
            post: {method:'POST', params: params}
        });

    // Trying to set this through a call to the API (needs to get param from route)
    $rootScope.$on('$routeChangeSuccess', function(event, current, previous) {
            var messages = data.rest.query({m_gid: $routeParams.gid}, function () { 
                data.messages = messages;
            });
    });

    return data;    
});

and the controllers are:

function MessagesCtrl ($scope, $http, $location, $routeParams, Messages) {
   $scope.messages = Messages.messages;
}

function MessageCtrl ($scope, $http, $location, $routeParams, Messages) {
   $scope.messages = Messages.messages[0];
}

But neither of the controllers update when the data loads from the REST API (I've logged the data coming back, and it definately does).

2 Answers 2

8

Instead of assigning a new array to data.messages like this:

data.messages = messages

use angular.copy() instead, which will populate the same array:

angular.copy(messages, data.messages)

That way, the controllers will see the update.

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that you are returning a different version of data to each controller. I would place messages in $rootScope. So

data.rest.query({m_gid: $routeParams.gid}, function () { 
            $rootScope.messages = messages;
        });

Incidentally, what is the purpose of setting the return value of data.rest.query to var messages? That variable gets blown as soon as you leave the function.

Comments

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.