我在啓動角度應用程序時通過腳本(init.js)連接到API。然後,我會收到som信息,例如用戶名和用戶ID,我想將它們定義爲全局值,以便在AngularJS應用程序中使用。將變量傳遞到AngularJS應用程序
如何傳遞變量以在AngularJS應用程序中使用?
我現在的想法是在MainController中定義變量以便能夠在任何地方使用它們。
init.js
(function() {
function appStart() {
//Get variables
var userId = 123;
var username = 'This is my name';
//Init Angular App
angular.bootstrap(document, ['myApp']); //How do I use the variables in the angular app?
}
function genericError() {
console.error('Something went wrong');
}
TT.native.init()
.done(appStart)
.fail(genericError);
})();
app.js
(function() { //Start
var app = angular.module('myApp', [
'myControllers',
'myDirectives',
'myFilters',
'myServices',
'ui.router'
]);
controller.js
var app = angular.module('myControllers', []);
app.controller('MainController', function ($scope, $state) {
$scope.userName = ""; //I want to use the variable from INIT.JS here
$scope.userId = 0; //I want to use the variable from INIT.JS here
});
你爲什麼不在角度應用程序中連接api? – 2014-10-22 09:33:03
我該怎麼做?我不知道如何。我正在使用這個基於jQuery的系統,它需要讓init代碼看起來像這樣。 – peta 2014-10-22 09:36:27
您可以爲您的第一個代碼塊構建服務(以獲取用戶數據)。然後,您可以在angularjs(app.run(...))內的一個運行塊中調用它。在那之後,當你需要這些變量時,你可以從那個服務中調用它們。我知道這對初學者來說可能太過分了,但這是一種一致的「角度」方式... – 2014-10-22 09:41:04