So I am trying to centralize the data service that passes all of the information back and forth between my application and the back-end services.
My application does not auto-bootstrap using ng-app="myApp", instead it loads the few modules it needs to load an external config file, and use that to get the initial data from the server before bootstrapping the application. Once the application gets bootstrapped, the feeds are assigned to the main controllers scope via $scope[feedName] = feedData. Because the feeds may vary, I've done this to ensure that the data is available to all scopes at all times.
Since I need to be able to use resource efficiently in this pre-bootstrapped scenario, I wrote a small function to get data called getDataFrom(url, data, method).
It looks like this:
getDataFrom = function(url, data, method){
// Create the defer for the data request
var dataDefer = $q.defer();
// Create the resource object to get the data using the supplied parameters
var getData = $resource(url, $.extend(data, {"callback": "JSON_CALLBACK"}), {query: {method: method}});
// Get the data from the resource object
getData.query().$promise.then(function(result){
dataDefer.resolve(result);
}, function(){
dataDefer.reject()
})
// Return the promise immediately
return dataDefer.promise;
};
It works perfectly in this scenario. Now, before I bootstrap my application, I assign a few constants, and this function is one of them:
app.constant("getDataFrom", getDataFrom);
Then whenever a module needs to send/receive data it is included as a dependency:
.controller('myController', function ($scope, $rootScope, $location, $sanitize, getDataFrom)
From here I can simply make a call like this:
getDataFrom(myUrl, {myData:equalsThis}, "JSON").then(result){//do stuff})
The problem I am having happens inside the then part of this scenario. If I do anything involving the scope, such as $location.path('/newpath') or $scope.value = newValue, none of this will happen unless I manually run $scope.$apply(). Since this is supposed to be an easy way of handling data, this clearly won't cut it.
Can somebody please explain to me why my then is missing the bus of the $scope.$apply that gets run automatically?
Aucun commentaire:
Enregistrer un commentaire