簡體   English   中英

從控制器發送數據到工廠?

[英]Sending data to factory from controller?

我的工廠是:

 myAppServices.factory('ProfileData',['$http',  function($http){
            return{
            newly_joined:function(callback){
            $http.get(
//myUrl will be an url from controller.
                myUrl
            ).success(callback);
              }
    };

          }
                                            ]);

我有三個具有不同URL的控制器:

控制器1:

AppControllers.controller('ProfileListCtrl',['$scope','$state', '$rootScope', 'ProfileData', '$timeout',   function($scope, $state, $rootScope, ProfileData, $timeout ) {


    ProfileData.newly_joined(function(response) {
      var myUrl= "www.abc...." 
     //something goes there
});

     }]);

控制器2:

AppControllers.controller('ProfileListCtrl1',['$scope','$state', '$rootScope', 'ProfileData', '$timeout',   function($scope, $state, $rootScope, ProfileData, $timeout ) {


    ProfileData.newly_joined(function(response) {
      var myUrl= "www.abc...." 
     //something goes there
});

     }]);

控制器3為:

AppControllers.controller('ProfileListCtrl2',['$scope','$state', '$rootScope', 'ProfileData', '$timeout',   function($scope, $state, $rootScope, ProfileData, $timeout ) {


    ProfileData.newly_joined(function(response) {
      var myUrl= "www.abc...." 
     //something goes there
});

     }]);

由於URL不同,我想在不同的控制器中使用不同的數據,並且我在單個網頁上顯示所有三個詳細信息。

因此,如果在工廠中有任何發送“ myUrl”的方法,我可以使用它來提取數據。

注意:請不要建議我使用$ resource或$ routeparams,因為$ resource無法成功從json提取數據,並且我不想在頁面上使用大變量Url。

提前致謝

您需要做的就是向new_joined函數添加一個附加參數:

newly_joined:function(callback, myUrl){

另外,您應該使用.then而不是.success

您的工廠應該返回承諾而不是使用回調。

myAppServices.factory('ProfileData',['$http',  function($http){
    return function(myUrl) {
        return $http.get(myUrl);
    };
}]);

控制器

AppControllers.controller('ProfileListCtrl',['$scope', 'ProfileData', function($scope,ProfileData) {

    var myUrl= "www.abc....";
    var httpPromise = ProfileData(myUrl);

    httpPromise.then(function onFulfilled(response) {
        $scope.data = response.data;
    }).catch(function onRejected(response) {
        console.log("ERROR ", response.status);
    });

}]);

JSFiddle上DEMO

使用promise的優點是它們保留錯誤信息。

還要注意, myUrl作為參數發送到工廠。

有關使用promise優點的更多信息,請參見為什么從Promise然后方法進行回調是一種反模式?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM