Synchronization problems when sharing objects with Factory and $ watch

0

I'm trying to make a listing of places by neighborhood. This data comes from different URLs:

www.example.com/api/lugares/bairro/1

www.example.com/api/lugares/bairro/2

ID of the neighborhood is generated in a controller BairrosCtrl , which is where the user selects the neighborhood:

app.controller('BairrosCtrl', function($scope, selectedBairro, $location) {
    $scope.escolhaLugar = function(bairro) {
        $scope.$watch('bairro', function(newBairro) {
            if(newBairro) {
                selectedBairro.set(newBairro);
            }
        });
        $location.path('/lugares/');
    };
});

Note that the neighborhood is passed by parameter in function escolhaLugar(bairro) ;

Using Factory selectedBairro to try share neighborhood object I create: a variable to initialize, a GET method and another SET:

app.factory('selectedBairro', function(){
    var bairro = {}
    return {
        set: function(bairroSelecionado) {
            bairro = bairroSelecionado;
        },
        get: function() {
            return bairro;
        }
    };
});

To try to consume the shared data that comes from the GET function I use the following function ($ watch) in the controller LugaresCtrl :

app.controller('LugaresCtrl', function($scope, serviceLugares, $location, selectedBairro) {
    $scope.$watch(function() {
        return selectedBairro.get();
    }, function(newBairro) {
        if(newBairro) {
            $scope.bairro = newBairro;
            debugger; /*DEBUGGER 1*/
        }
    });
    debugger; /*DEBUGGER 2*/
    serviceLugares.getLugares($scope.bairro.id, function(data) {
        $scope.lugares = data.lugares;
    });
});

Seeing that $scope.bairro = newBairro I pass $scope.bairro.id per parameter to concatenate with the rest of the URL in Factory serviceLugares , which is responsible for the $ http request that accesses the API:

app.factory('serviceLugares', function($http){
    var lugaresList,
        obj = {};
    obj = {
        getLugares:function(id, callback) {
            if(lugaresList) {
                callback(lugaresList);
                return false;
            } 
            else {
                $http({
                    method: 'GET',
                    url: 'http://www.example.com/api/lugares/bairro/' + id
                }).success(function(data) {
                    obj.saveLugares(data);
                    callback(data);
                })
            }
        },
        saveLugares:function(data) {
            lugaresList = data;
        }
    }
    return obj;
});

In LugaresCtrl we have 2 debugger; . In DEBUGGER 1 the $scope.bairro value is correct. However, in DEBUGGER 2 $scope.bairro does not exist. BECAUSE DEBUGGER 2 IS EXECUTED BEFORE DEBUGGER 1 .

Does anyone give me strength?

    
asked by anonymous 15.11.2014 / 05:15

0 answers