Tom Tom - 5 months ago 40
Node.js Question

Select default value in a dropdown using Angular with EJS

I mixed EJS and Angular in a webapp, but now I'm having problems to load a default value for a dropdown (select element).
I use the same HTML file to add and update users.

I have a URL that return all values loaded in the dropdown, accessed in the Angular controller when the page loads.
This is the controller:

angular.module('app').controller('userCtrl', function($scope, $http) {
function getCities() {
$http.get('/rest/cities').then(function(response) {
vm.cities =;

The EJS sends the default value via response (as in this example):

router.get('/user', function(req, res) {
res.render('pages/user', { defatultCity: 10 });

The HTML builds the dropdown with this code:

<select id="city" name="city" class="form-control input-sm" required>
<option ng-repeat="x in cities" value="{{x.idCidade}}"> {{ x.Nome }} </option>

What I have 'unsuccessfully' tried so far (in the HTML):

  1. To validate value from Angular with value from EJS

    <option ng-repeat="x in cities" value="{{x.idCity}}" <%if (defaultCity == %> {{x.idCity}} <%) {%> selected <%}%> > {{ x.Nome }} </option>

  2. To insert a hidden input to hold the value in the HTML and inside the controller I added a JQuery

    <input type="hidden" id="defaultCity" value"<%=defaultCity%>" />

    // In the controller (it return an error - this.each is not a function)

I know these attempts are ugly, but I could not find a way to make it work yet. I'll be happy if someone knows how to do it.

PS: I would like to avoid passing all the city list of values from NodeJS to use EJS
command inside the HTML.

Thank you!


Add this piece of code at the end of your .ejs template

<script type="text/javascript">
        .value('myCity', <%- JSON.stringify(defaultCity) %>);

then inject the component in your controller:

app.controller('myCtrl', function ($scope, myCity) {

    function getCities() {
        $http.get('/rest/cities').then(function(response) {
        vm.cities =;

        // myCity must be an object - same as vm.cities[0], for example
        $scope.defaultCity = myCity;


and change your HTML file to have the default value

<select ng-model="defaultCity"
    ng-options="city as for city in cities track by"
    id="city" name="city" class="form-control input-sm" required >