0

我正在用一些使用json輸入的小部件製作Angularjs/nvd3儀表板。我有一個小工具可以工作,但是我想要的是重用一個Angular服務來根據每個小工具提供的不同url返回數據。如何根據變量輸入正確地重用AngularJS服務和控制器?

我的Javascript代碼:

var fixedUrl = "http://static_url/data.json"; 

var myApp = angular.module("nvd3myApp", ['nvd3ChartDirectives']); 

myApp.service('dataService', function($http) { 
    this.getData = function(callbackFunc) { 
     return $http.get(fixedUrl); 
    } 
}); 

myApp.controller('Widget3Controller', function($scope, dataService){ 
    //Get the data 
    dataService.getData().then(function(dataResponse) { 
     data = dataResponse.somelogictotransformit(); 

     eval 
     $scope.exampleData = [ 
      { 
       "key" : "Widget title", 
       "color" : "#1f77b4", 
       "values": data 
      }, 
     ]; 

     $scope.xAxisTickFormatFunction = function(){ 
      return function(d){ 
       return d3.time.format('%H:%M')(new Date(d)); 
      } 
     } 
     $scope.yAxisTickFormatFunction = function(){ 
      return function(d){ 
       return d3.format(',d')(d); 
      } 
     } 
    }); 
}); 

而在html代碼:

<div id="container" ng-controller="Widget3Controller" ng-app='nvd3myApp'> 
    <nvd3-multi-bar-chart [.......]></nvd3-multi-bar-chart> 
</div> 

所以我喜歡做的是有一個不同的URL(而不是使用fixedUrl)每個小部件,但我無法讓myApp的dataService採取額外的變量。

我想要做一些像dataService.getData(someUrl),並最好甚至使用相同的控制器基於一些HTML標籤的多個小部件。

感謝您的任何幫助。

+0

將URL傳遞到getData'dataService.getData(url)''怎麼辦? – dfsq

回答

0

可以使用。服務或.controller只需使用.value的你:

myApp.value('url', 'http://static_url/data.json'); 

,然後在你的控制器,它注入/服務

myApp.service('dataService', ['url', function($http) { 
    this.getData = function(callbackFunc) { 
     return $http.get(url); 
    } 
}]); 

這個值可以overrided - 只是redifine它。

另一種方式 - 與一些參數寫.factory(用於創建網址),然後返回URL字符串,並注入它在你的。服務或者乾脆扔在PARAMS你。服務這樣的:

myApp.service('dataService', function($http){ 
    return ({ 
     getData/*public*/:getData /*private*/ 
    }) 
    function getData(urlPath1, urlPath2){ 
     var url = "http://" + urlPath1 + urlPath2 + "/data.json"; 
     return $http.get(url); 
    } 
} 
//inside controller : 
dataService.getData(static_url, static_urlPart2).then(...) 
0

你爲什麼不使用指令?定義指令級別的URL ...

myApp.directive('widget3', function() { 
    return { 
     scope : { 
      url : '@' 
     }, 
     controler: 'Widget3Controller', 
     replace: true, 
     template :'<div><nvd3-multi-bar-chart [.......]></nvd3-multi-bar-chart></div>' 
    } 
}); 

..然後獲取URL作爲範圍。

myApp.controller('Widget3Controller', function($scope, dataService){ 
    //Get the data 
    dataService.getData($scope.url).then(function(dataResponse) { 
     data = dataResponse.somelogictotransformit(); 
相關問題