2014-09-05 88 views
-1

如何使用所获取的数据customersControllerAnotherCustomersController混淆在控制器

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?? 
}  

Full Details Here

+1

您需要张贴代码 – PSL 2014-09-05 20:28:17

+0

请检查这个答案http://stackoverflow.com/a/12233991/1223357 抽象逻辑负责提取数据到可重用的服务。 – Teq1 2014-09-05 21:15:23

回答

0

您可以共享使用$rootscope控制器之间的数据,但我不认为这是一个最好的数据使用因此我的解决方案包含角度服务的使用 - >plnkr

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; 
    }); 

}); 

A我一直重构你的代码,所以只有一个应用程序在页面上使用。如果你想使用一个以上的则必须手动引导他们 - >Read More