我有以下工厂定义的
.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");
}
};
}])
我可以使用工厂在状态更改之前解析并更新需要在其他范围内使用的变量吗?
这是我解决的方法
.state('dashboard.sales', {
url: '/sales',
templateUrl: './app/dashboard/partials/sales/sales.html',
controller: 'DashboardSalesCtrl',
resolve: {
currentRestaurant: function(currentRestaurantService) { return currentRestaurantService.getCurrentRestaurant(); }
}
})
这是我将解析和工厂服务注入我的控制器但更新无法正常工作的方式
.controller('DashboardCtrl', ['$rootScope', 'currentRestaurant', 'currentRestaurantService', function($scope, currentRestaurant, currentRestaurantService)