Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExpressJS variables in AngularJS - Mean Stack

I am building a MEAN application, one issue I have is that I want to give my users some sort of control over the routes used. So I want my server side code (expressJS) to set some variables in my client side code.

Essentially I want to be able to generate my client side JS from my server side code.

for example, in PHP I would probably do something along the lines of

<?php
echo <script>
echo  var test = $test
echo </script>
 ?>

I am not talking about binding, the variables only need to be set at the initial application load.

What would be the best way to accomplish this kind of integration with MEAN, in the cleanest way possible...

like image 566
Melbourne2991 Avatar asked Jan 17 '26 18:01

Melbourne2991


2 Answers

Just an other approch

router.js
app.get('/myconfig', function(req, res){
    var config = {prop1:1,myarray:[1,2,3]};
    var json = JSON.stringify(config);
    res.end('var config='+json);
});
jade
script(type='text/javascript', src='/myconfig')

than in angular you can do

angular.module('yourApp').constant('setup', config)
like image 88
Whisher Avatar answered Jan 19 '26 16:01

Whisher


Option 1

First write an api endpoint that will return your configurations.

app.get('/conf', function(req, res) {
    res.send(200, {
        foo: "bar"
    });
});

Then do a $http.get to this endpoint and retrieve the configuration object on angular app.run and store this configuration in a service/$rootScope/config.

app.run is the closest thing in angular to a main() function and will run once when the application starts.

Option 2

Use grunt.

If your solution does not need to explicitly get the variables from server side, and if they are known at the time you deploy the application, you can do a javascript compile and inject the configurations using grunt.

This is how I have personally handled this situation.

like image 36
ncabral Avatar answered Jan 19 '26 15:01

ncabral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!