A
A
akamoroz2013-09-17 13:24:26
JavaScript
akamoroz, 2013-09-17 13:24:26

[AngularJS] communication between service and controller data

During the development process, there were problems with the connectivity of links between the service and the controller.
Let me explain with an example:

// Есть сервис, в нем хранится id и другие данные.
app.service('testService', function ($http, serverURL, $timeout) {
    var self = this;
    self.data = {
        id: null,
        token: null,
        ....
    };
    self.initMe = function () {
        return $http({
            method: 'GET',
            url: serverURL + '/initMe/' + '?token=' + self.data.token
        });
    };
    return self;
});
meModule.controller('MeCtrl', function (...) {
    $scope.me = testService.data; // устанавливаем связь между scope и service

    $rootScope.$on('initMe', function (e, data) {

        testService.initMe().success(function (data, status, headers, config) {
            // data.result - object
            // $scope.me = data.result;         // не работает
            // или
            // meService.data = data.result;    // не работает

            meService.data = data.result;       //  
            $scope.me = meService.data;         // Всё ок - приходится восстанавливать связь между scope и service :(
        });
    });
}


Questions:
1. Why do we lose the connection between scope and service on the lines $scope.me = data.result or meService.data = data.result;?
2. Are there other, more beautiful ways to update data in services from an external API (GET requests)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan Lopatin, 2013-09-17
@lorus

Because testService.dataand $scope.meare different references. If you want both of these references to point to the same object, then update both of them.
But why do you need two links? Just put in $scopea link to your service and update the data only in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question