我正在使用AngularJS和D3.JS
我有一个html表单,其中包含以下内容:
<div simple-chart chart-data="lineData"></div>
这与如此指令挂钩:
mist.directive("simpleChart", function($window, $http){
return{
restrict: "EA",
template: "<svg width='750' height='200'></svg>",
link: function(scope, elem, attrs){
function drawLineChart() {
//initilize the line chart
}
$http.get("myurl")
.success(function(data, status, headers, config){
drawLineChart();
})
}}
});
答案 0 :(得分:1)
您可以将http调用包装到服务中,并使用类似angular-cache的内容来缓存服务器的响应。
答案 1 :(得分:0)
您可以创建一个返回$ http.get('myurl')的服务,并将其作为指令中的依赖项添加。
mist.factory('dataService', function ($http) {
var dataService= {};
dataService.getData = function(){
return $http.get('myurl');
}
return dataService;
});
mist.directive("simpleChart", function($window, dataService){
return{
restrict: "EA",
template: "<svg width='750' height='200'></svg>",
link: function(scope, elem, attrs){
function drawLineChart() {
//initilize the line chart
}
dataService.getData()
.success(function(data, status, headers, config){
drawLineChart();
})
}}
});
答案 2 :(得分:0)
由于我使用AngularJS1.3,我需要使用
mist.factory('dataService', function ($http) {
return {
getData: function () {
//since $http.get returns a promise,
//and promise.then() also returns a promise
//that resolves to whatever value is returned in it's
//callback argument, we can return that.
return $http.get('http://url.com').then(function (result) {
return result.data;
});
}
};
});
mist.directive("simpleChart", function ($window, dataService) {
return{
restrict: "EA",
template: "<svg width='750' height='200'></svg>",
link: function (scope, elem, attrs) {
function drawLineChart() {
//initilize the line chart
}
dataService.getData().then(
function (data) {
drawLineChart();
},
function (err) {
console.log("Sorry we encountered an error " + err);
}
);
}};
});
消息来源:http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html