angular创建与控制器和服务交互的指令

时间:2013-06-19 17:26:37

标签: javascript angularjs

我正在进行重构。我有一个由我的控制器调用的服务“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);
    });

});

0 个答案:

没有答案