2014-10-22 25 views
0

我在啓動角度應用程序時通過腳本(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 
}); 
+0

你爲什麼不在角度應用程序中連接api? – 2014-10-22 09:33:03

+0

我該怎麼做?我不知道如何。我正在使用這個基於jQuery的系統,它需要讓init代碼看起來像這樣。 – peta 2014-10-22 09:36:27

+0

您可以爲您的第一個代碼塊構建服務(以獲取用戶數據)。然後,您可以在angularjs(app.run(...))內的一個運行塊中調用它。在那之後,當你需要這些變量時,你可以從那個服務中調用它們。我知道這對初學者來說可能太過分了,但這是一種一致的「角度」方式... – 2014-10-22 09:41:04

回答

1

最簡單的解決辦法是:

var userId = -1; 
var username = ''; 
(function() { 
function appStart() { 
    //Get variables 
    userId = 123; 
    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.controller('MainController', function ($scope, $state) { 
    $scope.userName = userId; 
    $scope.userId = username; 
}); 

但是隻知道這是不是一個好方法。您應該在角度應用程序內連接到您的api。也許你應該在開始編碼之前觀看和閱讀一些教程...

+0

謝謝!這是不是一個好方法?我非常希望看到我可以在Angular應用程序中做到這一點。在第一個狀態加載之前。如果我現在可以在init.js中執行相同的事情,那當然會很棒! – peta 2014-10-22 10:22:00

+0

開始挖掘服務(工廠方法)和angularjs的運行方法。如果這是目前的解決方案,請接受此爲正確答案。 – 2014-10-22 10:29:06

+0

沒問題,雖然知道它是一種不好的方法,但我可以分析它是否是一個持久的解決方案。 – peta 2014-10-22 10:36:10

0

您可以使用angular.module('myApp').valueangular.module('myApp').constant在自舉之前。在你的控制器中,你應該添加變量到依賴項中。

+0

謝謝!聽起來像一個好方法。你能舉個例子嗎?我不是一個有經驗的編碼員。 – peta 2014-10-22 09:47:50

+0

好的,我可以添加這些值。但是,如何在引導角度時將變量設置爲.value? – peta 2014-10-22 10:13:50

+0

angular.module('myApp')。value('userName',userName) – Mikalai 2014-10-22 10:22:16

0

您可能使用ngRouter或uiRouter,因此您可以在進入第一個路由/狀態之前resolveTT.native.init

+0

是的,使用Ui路由器。我會怎麼做?你能把它放到代碼中嗎? – peta 2014-10-22 09:51:42