jean-Philippe jean-Philippe - 4 months ago 16
HTML Question

Render html files with EJS with angular in it

I have a node + angular project. I want to render a html page and init it with some values. I wan thoses values to be linked to the Angular scope.

So i have an input, I linked it with ng-model but this erase the EJS initialisation.

server.js:

var express = require('express');
var app = express();
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/front/views');
app.set('view engine', 'html');
app.use('/front',express.static(__dirname + '/front'));

app.get('/signup',function(req,res){
res.render('view',{
user:{
email:"user mail",
}
})
});
var port = 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});


view.html:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>

<script src="/front/controllers/app.js"></script>

<html ng-app="onboardingApp">

<form id="msform" novalidate ng-controller="onboardingController">

<input required type="text" name="email" ng-model="signup.user.email">
<label for="email">Email</label>

<input type="button" name="next" ng-click="displaySignup()" value="NEXT"/>

</form>

</html>


app.js:

var onboardingApp = angular.module('onboardingApp', []);

onboardingApp.controller('onboardingController',function OnboardingController($scope) {

$scope.signup = {
user:{
email:""
}
}

$scope.displaySignup = function(){
console.log($scope.signup)
}

});


So I am trying to set the value of:
input required type="text" name="email" ng-model="signup.user.email"


with ejs and then that this value to be linked with the angular model
signup.user.email.


Can someone help me with that?

Answer

you can add this piece of js at the end of your view.html

<script type="text/javascript">
      angular.module('onboardingApp')
        .value('userEmail', <%- JSON.stringify(user.email) %>);
</script>

and then inject the component wherever you need it like so:

onboardingApp.controller('onboardingController',
 function OnboardingController($scope, userEmail) {

    $scope.signup = {
        user:{
            email: userEmail
        }
    }

    $scope.displaySignup = function(){
        console.log($scope.signup)
    }

});
Comments