执行的看来,工厂方法执行优先级是最高的,因此回调没有数据来处理。做这项工作的最佳方式是什么?
我得到了这样的工厂
app.factory('jsonService', function($http) {
return {
getDistricts: function(callback) {
$http.get('data/districts.json').success(callback);
},
getLocations: function(path,callback) {
$http.get('data/'+path+'.json').success(callback);
}
};
});
和控制器
var app = angular.module('sandbox', []);
app.controller('sandboxCtrl',function ($scope,jsonService) {
//This one works
$scope.init1= function(){
jsonService.getDistricts(function(data){
$scope.districts = data;
$scope.currentDistrict = $scope.districts[0].name;
jsonService.getLocations($scope.currentDistrict,function(data){
$scope.locations1 = data;
})
});
};
$scope.init1();
//This one does not
$scope.init2= function(){
jsonService.getDistricts(function(data){
$scope.districts = data;
$scope.currentDistrict = $scope.districts[0].name;
})
jsonService.getLocations($scope.currentDistrict,function(data){
$scope.locations1 = data;
});
};
$scope.init2();
});
这里的工作plunker
+1 OP:我认为你应该接受这个答案,它比我的好得多。然而,看看我在答案中给出的例子,它们可能是这个例子的一个很好的补充。 – Josep 2014-10-08 14:09:54
另外,请注意,打开服务中的承诺并不是一个好主意,因为这增加了不必要的耦合到您的工厂。 – Josep 2014-10-08 14:14:09
非常感谢这些信息。但是,我仍然可以使用这种方法在分离函数中调用.getLocations,还是必须将它绑定到.success()或.then()方法? – 2014-10-08 14:28:23