1

我正在进行重构。我有一个由我的控制器调用的服务“myservice”,它基本上使 get 请求用重组数据填充 $scope 变量。

我希望能够为我的小部件创建一个指令,将服务注入其中,但我不确定如何组织我的代码。我希望能够使用我的指令中定义的属性从我的控制器中调用服务。

我希望我的指令看起来像这样..

<mywidget service="MyService" server="http://localhost:8080/" api="abcservice"/>

我的服务目前看起来像这样......

 .service('MyService',function($http, $q){
  return{

        getPageData: function(server,api){
            //Creating a deferred object
            var deferred = $q.defer();

            //Calling Web API to fetch data - this is just hacky right now
            $http.get(server+api).success(function(data){
                //Passing data to deferred's resolve function on successful completion
                deferred.resolve(data);
            }).error(function(){
                    //Sending a friendly error message in case of failure
                    deferred.reject("An error occured while fetching items");
                });

            //Returning the promise object
            return deferred.promise;
        }
    }
 }

最后是控制器......我如何使用从指令属性传递的数据?

myapp.controller('MainCtrl',  function($scope, MyService) {   
     $scope.cleanData = function(res){
      // magical things happen including assigning some cleaned data to a controllers scope variable
    }    


    //not sure how to get server and api that i had in the directive
    MyService.getPageData(???????).then(function(res){
        $scope.cleanData(res);
    });

});
4

0 回答 0