Using factory service for resolve and to hold variable across controllers

50 views Asked by At

I have the following factory defined

.factory('currentRestaurantService', ['$rootScope', '$q', function($scope, $q) {
    var currentRestaurant;

    return {
        getCurrentRestaurant: function() {
             if(typeof currentRestaurant == 'undefined'){
                var defer = $q.defer(); // Create a deferring object
                $scope.currentUser = Parse.User.current();

                // Get restaurant for user
                var restaurantObject = Parse.Object.extend("Restaurant");
                var query = new Parse.Query(restaurantObject);
                var thisUsersRestaurants = query.equalTo("user", $scope.currentUser);

                thisUsersRestaurants.find().then(function(restaurants) {
                    currentRestaurant = restaurants[0];
                    defer.resolve(restaurants[0]);
                });

                return defer.promise; // Create an Angular promise to be resolved
            } else {
                var defer = $q.defer();
                defer.resolve(currentRestaurant);
                return defer.promise;
            }
        },

        updateCurrentRestaurant: function(newRestaurant) {
            currentRestaurant = newRestaurant;
            $scope.$broadcast("newCurrentRestaurant");
        }
    };
}])

Can I use a factory to both resolve before a state change and to also update a variable that needs to be available across other scopes?

This is how I resolve

.state('dashboard.sales', {
        url: '/sales',
        templateUrl: './app/dashboard/partials/sales/sales.html',
        controller: 'DashboardSalesCtrl',
        resolve: {
            currentRestaurant: function(currentRestaurantService) { return currentRestaurantService.getCurrentRestaurant(); }
        }
    })

This is how I injected both the resolve and factory service into my controller but update doesn't work properly

.controller('DashboardCtrl', ['$rootScope', 'currentRestaurant', 'currentRestaurantService', function($scope, currentRestaurant, currentRestaurantService)
0

There are 0 answers