Javascript 如何基于变量输入正确重用AngularJS服务和控制器?
我正在制作一个Angularjs/nvd3仪表板,其中包含许多使用json输入的小部件。我有一个小部件要工作,但我尝试的是重用Angular服务,根据每个小部件提供的不同url返回数据 我的Javascript代码:Javascript 如何基于变量输入正确重用AngularJS服务和控制器?,javascript,angularjs,angularjs-service,angularjs-nvd3-directives,Javascript,Angularjs,Angularjs Service,Angularjs Nvd3 Directives,我正在制作一个Angularjs/nvd3仪表板,其中包含许多使用json输入的小部件。我有一个小部件要工作,但我尝试的是重用Angular服务,根据每个小部件提供的不同url返回数据 我的Javascript代码: var fixedUrl = "http://static_url/data.json"; var myApp = angular.module("nvd3myApp", ['nvd3ChartDirectives']); myApp.service('dataService'
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.getData(someUrl)的事情,甚至最好使用同一个控制器来基于一些html标记的多个小部件
感谢您的帮助。您可以在使用.service或.controller时使用.value:
myApp.value('url', 'http://static_url/data.json');
然后将其注入控制器/服务
myApp.service('dataService', ['url', function($http) {
this.getData = function(callbackFunc) {
return $http.get(url);
}
}]);
此值可以重写-只需重新定义即可
另一种方法-使用一些参数编写.factory(用于url创建),然后返回url字符串,并将其注入到.service中,或者简单地在.service中抛出参数,如下所示:
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(...)
你为什么不使用指令呢?在指令级别定义URL
myApp.directive('widget3', function() {
return {
scope : {
url : '@'
},
controler: 'Widget3Controller',
replace: true,
template :'<div><nvd3-multi-bar-chart [.......]></nvd3-multi-bar-chart></div>'
}
});
将url传递到getData
dataService.getData(url)
中怎么样?
myApp.controller('Widget3Controller', function($scope, dataService){
//Get the data
dataService.getData($scope.url).then(function(dataResponse) {
data = dataResponse.somelogictotransformit();