跨控制器共享数据的“Angular 方式”是使用服务:
app.factory('ProductOwners', function ($http) {
var service = {
data: []
};
$http({
url: "php/functions.php",
method: "GET",
params: {
action: "get_product_owners"
}
}).success(function(data) {
service.data = data;
});
return service;
});
然后在每个控制器中注入服务:
app.controller('someCtrl', function (ProductOwners) {
$scope.product_owners = ProductOwners.data;
});
具有“惰性”评估的不同实现(即,它仅在需要时进行调用,然后提供相同的数据):
app.factory('ProductOwners', function ($http, $q) {
var data;
function getDataIfNeeded() {
if (data !== undefined) {
return $q.when(data);
}
return $http({
url: "php/functions.php",
method: "GET",
params: {
action: "get_product_owners"
}
}).then(function(response) {
data = response.data;
return data;
});
}
return {
getData: getDataIfNeeded
};
});
app.controller('someCtrl', function (ProductOwners) {
ProductOwners.getData().then(function (data) {
$scope.product_owners = data;
});
});
更新
另一个不同的实现,带有“惰性”评估并支持传递给的参数getData()
:
app.factory('GenericService', function ($http, $q) {
var data = {};
function getDataIfNeeded(action) {
action = action || 'default';
if (data[action] !== undefined) {
return $q.when(data[action]);
}
return $http({
url: "php/functions.php",
method: "GET",
params: {
action: action
}
}).then(function(response) {
data[action] = response.data;
return data[action];
});
}
return {
getData: getDataIfNeeded
};
});
app.controller('someCtrl', function (GenericService) {
GenericService.getData("get_product_owners").then(function (data) {
$scope.product_owners = data;
});
});