Angularjs 如何使用Angular JS在页面加载时调用函数
我有一个角度控制器,它有一系列函数,它们之间共享数据。问题是,我从函数1返回的数据在函数2中使用,然后在函数2中返回的数据在函数3中使用。我的问题是函数2和函数3先执行,并且说找不到数据。有没有办法安排函数1先执行 以下是我的代码供参考:Angularjs 如何使用Angular JS在页面加载时调用函数,angularjs,Angularjs,我有一个角度控制器,它有一系列函数,它们之间共享数据。问题是,我从函数1返回的数据在函数2中使用,然后在函数2中返回的数据在函数3中使用。我的问题是函数2和函数3先执行,并且说找不到数据。有没有办法安排函数1先执行 以下是我的代码供参考: $scope.Read = function () { var get = ServiceName.Read(); getConfig.then(function (d) { $scope.RID = d.data;
$scope.Read = function () {
var get = ServiceName.Read();
getConfig.then(function (d) {
$scope.RID = d.data;
alert($scope.RID);
}, function (error) {
$log.error('Oops! Something went wrong while fetching the application key data.' + error)
})
}
$scope.Read();
$scope.getApp = function () {
var sub ={
"RID": $scope.RID
}
var App = ServiceName.getApp(sub);
App.then(function (d) {
$scope.LID = d.data.BUser;
}, function (error) {
$log.error('Opps! Something went wrong in getting appplication defaults');
});
}
$scope.getApp();
我想使用数据的功能2:
$scope.Read = function () {
var get = ServiceName.Read();
getConfig.then(function (d) {
$scope.RID = d.data;
alert($scope.RID);
}, function (error) {
$log.error('Oops! Something went wrong while fetching the application key data.' + error)
})
}
$scope.Read();
$scope.getApp = function () {
var sub ={
"RID": $scope.RID
}
var App = ServiceName.getApp(sub);
App.then(function (d) {
$scope.LID = d.data.BUser;
}, function (error) {
$log.error('Opps! Something went wrong in getting appplication defaults');
});
}
$scope.getApp();
任何帮助都将不胜感激
谢谢大家!
致以最良好的祝愿
Sandeep
< P>如果需要初始化某个东西,可以考虑使用CONFIG或Run:angular.module('myModule', []).
config(function(injectables) {
}).
run(function(injectables) {
});
请参阅此处的详细信息:如果前两个是对返回承诺的服务的调用,看起来它们是。无法调用.Then()中的函数吗 例如:
$scope.functionOne(){
CallToService().then(function(data){
//Success call Function 2
$scope.functionTwo(data);
},function Error(){
//Error/
}
};
$scope.functionTwo(){
CallToService2().then(function Success(data){
//Call function 3
$scope.function3(data);
},
function Error(){
//Error
}
}
这是因为服务是异步调用的。你可以在下一次服务中连锁承诺并返回你需要的价值,等等
getConfig.then(函数(d){
返回数据;
},函数(错误){
}).then(函数(res){
//使用第一个服务返回的值调用第二个服务
}).然后(功能(res){
//使用第二个服务返回的值调用第三个服务
})
因此,我可以像您所说的那样执行该函数,但即使在我看到该函数第一次执行之后,作用域仍然表示下一个函数$scope.getApp=function(){Read();//在这里调用函数1 var sub={“RID”:$scope.RID}var App=ServiceName.getApp(sub);App.then(函数(d){$scope.LID=d.data.BUser;},函数(error){$log.error('Opps!获取应用程序默认值时出错');});}$scope.getApp();是的,我这样做了,但是我需要将一个值传递给函数2,它总是说作用域未定义。我不确定我到底出了什么问题