Angularjs 关于控制器中数据使用的困惑
如何在Angularjs 关于控制器中数据使用的困惑,angularjs,angularjs-scope,angularjs-controller,Angularjs,Angularjs Scope,Angularjs Controller,如何在另一个CustomerController function customersController($scope, $http) { $http.get("http://www.w3schools.com//website/Customers_JSON.php") .success(function(response) {$scope.names = response;}); } function AnotherCustomersController($scope){
另一个CustomerController
function customersController($scope, $http) {
$http.get("http://www.w3schools.com//website/Customers_JSON.php")
.success(function(response) {$scope.names = response;});
}
function AnotherCustomersController($scope){
//What should I do here??
}
您可以使用在控制器之间共享数据,但我认为这不是最佳做法,因此我的解决方案包含使用角度服务->
此外,我还重构了您的代码,因此页面上只使用了一个应用程序。如果您想使用多个,您必须手动引导它们->您需要发布代码,请检查此答案负责将数据提取到可重用服务的抽象逻辑。
app.factory('CustomerService', function ($http) {
return {
fetchData: function () {
return $http.get('http://www.w3schools.com//website/Customers_JSON.php')
}
}
});
app.controller('customersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});
app.controller('AnotherCustomersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});