使用AngularJS在两个不同的指令中调用相同的$http.get()
Call the same $http.get() in 2 different directives using AngularJS
我正在使用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();
})
}}
});
- 是否有可能使用$http.get("myurl")的数据创建另一个指令,而不必再次调用它?
- 是否有可能使$http.get("myurl")通用,以便它可以被不同的指令调用?
- 我可以用这样的东西吗?无法从jQuery Ajax调用中获得正确的返回值
你可以把你的http调用包装成一个服务,并使用类似angular-cache的东西来缓存来自服务器的响应。
你可以创建一个返回$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();
})
}}
});
因为我使用的是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
相关文章:
- 如何在调用下一个请求之前完成第一个Ajax Get请求
- 在发布后调用jQuery Get
- 如何检查$httpBackend中是否未进行GET调用
- 当用$.getScript()加载脚本时,有一种方法可以从用$.get script()装载的脚本中调用父脚本中的函数
- 将c#get方法a转换为post方法,从javascript调用
- CakePHP错误:在非对象上调用成员函数get(),使用cakejavascript助手时出错
- 成功函数未在 ajax GET 方法中调用
- JQuery AJAX - 如何使用方法 GET 调用刷新/重新加载页面
- 调用$.get函数时JQuery中出现无效标签错误
- 由于浏览历史设置,angularjs http.get调用未在ie10中启动
- 得到"未捕获的类型错误:未定义的不是函数“;当试图从对象调用get()或set()时
- 余烬数据断言失败:无法对未定义的对象使用“查询”调用 get
- 循环不'调用$.get时无法按预期工作
- 如何将ng-model传递给控制器函数,该控制器函数会向nodeJS服务器调用GET请求
- 使用POST方法调用REST api会调用GET方法
- 为什么IE9在按enter键时调用get方法而不是post,如何修复?
- Sequelize:调用.get({plain: true}))返回.get不是函数
- jQuery ajax调用(.get、.post.、.load等),返回数据和IE问题
- 在 AngularJS 中调用 GET 后,控制器内对象的值不会更改
- 如何从html文件中的li标签调用get属性