如何在angularjs工厂中调用函数
How to call function in angularjs factory
这是我的工厂,我想在saveData中调用getData。这是我的代码
.factory('dataSyncOperation', function($q,$http){
return {
getData:function(){
var q = $q.defer();
var config = {
headers : {
'Content-Type': 'application/json'
}
}
$http.get(api+'/sync/').then(function(response){
q.resolve(response);
},function(error){
q.reject();
})
return q.promise;
},
saveData:function(){
}
}
});如何使用getData返回的承诺到saveData.
你可以这样做-
saveData:function(){
this.getData().then(function(response){ // you can handle getData promise here
// on success
}, function(reject){
// on failure
});
}
在你的saveData
方法中,让我知道这是否是你正在寻找的东西。
工作示例- http://plnkr.co/edit/y8WZQT8SvOAWpKj8Jgxs?p=preview
——代码
// Code goes here
var myApp = angular.module('myApp', []);
myApp.controller('mainCtrl', function($scope, testService){
testService.saveData().then(function(res){
$scope.test = res.data;
});
})
myApp.factory('testService', function($q, $http){
return {
getData:function(){
var q = $q.defer();
$http.get('data.json').then(function(response){
q.resolve(response);
}, function(error){
q.reject();
})
return q.promise;
},
saveData:function(){
return this.getData();
}
}
})
您不必在返回的对象字面量中声明所有函数。你可以这样做:
factory('dataSyncOperation', function($q,$http){
function getData(){ //you can declare function inside function and it will be avaible only inside scope of outer function
var q = $q.defer();
var config = {
headers : {
'Content-Type': 'application/json'
}
}
$http.get(api+'/sync/').then(function(response){
q.resolve(response);
},function(error){
q.reject();
})
return q.promise;
}
getData(); //call get data
function saveData() {
myPrivateFunction();
getData(); //call get data inside save data
}
function myPrivateFunction(){ //you can even have private functions not avaible from outside
}
return { //declare which functions will be available from outside
getData:getData,
saveData:saveData
}
});
这种方式更可取。请查看angular的样式指南
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量