Search code examples
javascriptangularjsselectangular-ngmodel

AngularJS ng-model on select input doesn't work


I'm starting with AngularJS and tried to do a and get its value with Angular, but it doesn't work.

<div id="app_container" ng-controller="ArticlesController as control">
<select name="sortby" id="sortby" ng-model="sortBy"> {{sortBy}}
    <option name="Date" value="Date">Date</option>
    <option name="Vues" value="Vues">Vues</option>
    <option name="Note" value="Note">Note</option>
    <option name="Catégorie" value="Catégorie">Catégorie</option>
    <option name="Tags" value="Tags">Tags</option>
</select>
<div>

Here I want to display the value of the select input, but it displays nothing. I can't access this value from the controller neither, and I don't understand why. I have a ng-repeat on the same page that works perfectly well. I even tried to copy past the example from angularjs.org, even this doesn't work...


Solution

  • Since you are using controller as syntax, you need to use ng-model="controlsortBy"

    DEMO

    var app = angular.module('testApp',[]);
    app.controller('ArticlesController',function(){
       var control = this;
       control.print = function(){
         console.log(control.sortBy);
       }
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <body ng-app="testApp">
    <div id="app_container" ng-controller="ArticlesController as control">
    <select name="sortby" id="sortby" ng-change="control.print()" ng-model="control.sortBy">
        <option name="Date" value="Date">Date</option>
        <option name="Vues" value="Vues">Vues</option>
        <option name="Note" value="Note">Note</option>
        <option name="Catégorie" value="Catégorie">Catégorie</option>
        <option name="Tags" value="Tags">Tags</option>
    </select>
    <h1> {{control.sortBy}}</h1>
    <div>