Angularjs 如何在初始化之前等待相关模块运行功能完成
我正在尝试开发一个应用程序,其中一个模块将依赖于第二个模块。在第一个模块运行函数中,我试图使用http从服务器用一些数据填充templatecache,但是由于http调用是异步的,我的第二个模块将在第一个模块完成之前运行,并且结果中没有定义。下面的代码将使情况更加清楚Angularjs 如何在初始化之前等待相关模块运行功能完成,angularjs,Angularjs,我正在尝试开发一个应用程序,其中一个模块将依赖于第二个模块。在第一个模块运行函数中,我试图使用http从服务器用一些数据填充templatecache,但是由于http调用是异步的,我的第二个模块将在第一个模块完成之前运行,并且结果中没有定义。下面的代码将使情况更加清楚 var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$
var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
$timeout(function () {
$templateCache.put('ajay', 'ajay');
}, 1000);
}
]);
var secondapp = angular.module('plunker', ['main']);
secondapp.controller('test', function ($scope, $templateCache, $timeout) {
// get me undefined i want to wait until module main is finished running run function
alert($templateCache.get('ajay'));
});
拥抱异步性:
var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
$templateCache.put('ajay', $http.get("/data/ajay"));
}
]);
var secondapp = angular.module('plunker', ['main']);
secondapp.controller('test', function ($scope, $templateCache, $timeout) {
$templateCache.get('ajay').then(function (data) {
alert(data);
});
});
拥抱异步性:
var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
$templateCache.put('ajay', $http.get("/data/ajay"));
}
]);
var secondapp = angular.module('plunker', ['main']);
secondapp.controller('test', function ($scope, $templateCache, $timeout) {
$templateCache.get('ajay').then(function (data) {
alert(data);
});
});
就像你想在第一个应用程序中从回调运行第二个应用程序一样。如果在第一个应用的成功回调中触发了
ng,那么将两个应用都放在主页上,在第二个应用中加载ng,这会很糟糕吗?我不知道,我还没试过..就好像你想在第一个应用程序中从回调运行第二个应用程序一样。如果在第一个应用的成功回调中触发了ng,那么将两个应用都放在主页上,在第二个应用中加载ng,这会很糟糕吗?我不知道,我还没试过..接受异步,是的,但不是在不存在异步的地方$templateCache.get()不返回承诺,而是返回数据。接受异步性,是的,但不要在不存在异步性的地方$get()不返回承诺,而是返回数据。