简体   繁体   中英

Pass variables into AngularJS App

I am connecting to an API through a script (init.js) when starting my angular app. I then receive som information such as a username and a user ID that I want to define as global values to use in the AngularJS App.

How do I pass the variables on to use in the AngularJS app?

My thought now is to define the variables in the MainController to be able to use them anywhere.

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
});

The easiest solution would be:

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);
})();

Then in the controller:

app.controller('MainController', function ($scope, $state) {
    $scope.userName = userId;
    $scope.userId = username;
});

But just know that this is not a good approach. You should connect to your api within the angular app. Maybe you should watch and read some tutorials before beginning to code...

You can use angular.module('myApp').value or angular.module('myApp').constant before bootstrapping angular. In your controller you should add variables into dependencies.

您可能使用ngRouter或uiRouter,因此可以在输入第一个路由/状态之前resolve TT.native.init

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM