Javascript 从控制器向工厂发送数据?

Javascript 从控制器向工厂发送数据?,javascript,angularjs,angularjs-directive,angular-ui-router,angular-services,Javascript,Angularjs,Angularjs Directive,Angular Ui Router,Angular Services,我的工厂是: myAppServices.factory('ProfileData',['$http', function($http){ return{ newly_joined:function(callback){ $http.get( //myUrl will be an url from controller. myUrl ).success(callba

我的工厂是:

 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


提前感谢

您只需向新加入的函数添加一个附加参数:

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

}]);

使用承诺的优点是它们保留错误信息

还要注意,
myUrl
作为参数发送到工厂


有关使用承诺的好处的更多信息,请参见

根据控制器的不同,您希望返回不同的数据吗?如果是这样的话,为什么不创建3个单独的方法(我认为这是最好的设计),或者只给
新加入的
传递一个名称,比如
新加入的(“profile”)
新加入的(“profile1”)
(不是很好的解决方案)?我还应该提到
$http
上的
成功
回调是不推荐的,看见你应该使用
然后改为
。hi@georgeawg,你能在这里创建一个plunker吗,因为我得到如下错误:你可以使用这个json文件作为示例:hi@austin,你能为它创建一个plunker示例吗。如果是,那就太好了。