Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing NODE_ENV to Angular

I have an Angular, Node based app. It uses Jade for templating. I want to hide or show chunks of my page depending on the NODE_ENV variable that I use to start node with.

Something like this (not sure about how to check "else not" with ng-if):

div(ng-if="testingmode")
    {{somescopevar}}

div(ng-if != "testingmode")
    {{differentscopevar}}

The kicker is that testingmode is determined by what the NODE_ENV variable is. I can access that variable within my jade templates but don't know how to get it into my Angular scope.

tl;dr: How do I get NODE_ENV into my Angular scope?

like image 835
Lothar Avatar asked May 13 '26 04:05

Lothar


2 Answers

Personally I would create an api call that returns that value, and then have angular grab it in a controller using $http.

In your node routes:

app.get('/nodeenv', function(req, res, next){
    return res.json({ env: app.get('env') });
});

In your angular controller:

$http.get('/nodeenv').success(function(data){
    $scope.myEnvironment = data.env;
});

UPDATE:

A new way I have been doing this with newer projects is generating my root index file as a template in node (eg. with doT templates). Then passing any constants into the template to be loaded directly into angular. Below is the way you could pass in the environment for example:

index.def

<html>
<head><!-- head stuff --></head>
<body>
    <div>scripts and content go here</div>

    <!-- initialise any templated constants -->
    <script>
        angular.module('mymodule').constant('globals', {
            env: '{{=it.env}}'
        });
    </script>
</body>
</html>
like image 144
Matt Way Avatar answered May 15 '26 17:05

Matt Way


As an alternative you could put this in your build system with gulp-replace. I'm sure grunt has a similar feature.

index.html

<script>
  var ENV = 'NODE_ENV'; // replaced by gulp
</script>

gulpfile.js

gulp.task('setEnv', function(){
  gulp.src(['index.html'])
  .pipe(replace(/NODE_ENV/g, process.env.NODE_ENV))
  .pipe(gulp.dest('build/index.html'));
});

Haven't test the exact code, but you get the gist.

like image 45
Michael Cole Avatar answered May 15 '26 18:05

Michael Cole



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!