Tom
Tom

Reputation: 1411

Select default value in a dropdown using AngularJS with EJS

I mixed EJS and AngularJS 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 = response.data.records;
        });
    }

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></option>
        <option ng-repeat="x in cities" value="{{x.idCidade}}"> {{ x.Nome }} </option>
    </select>

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)
    $('city').val($('#defaultCity'))
    

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 forEach command inside the HTML.

Thank you!

Upvotes: 0

Views: 1817

Answers (1)

Karim
Karim

Reputation: 8632

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

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

then inject the component in your controller:

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

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

        // 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 city.name for city in cities track by city.id"
    id="city" name="city" class="form-control input-sm" required >
    <option></option>
</select>

Upvotes: 1

Related Questions