Search code examples
angularjsangular-ngmodelng-optionsangularjs-ng-changeangularjs-select

Can't set a default value on select>option when using ngChange="myFunction()" in my angular app


I'm building an angular app ; and I have to set a default value coming from $scope.ecole.niveauid of my controller. To do so, I just wrote this code :

<select class="form-control" name="niveau">
      <option value="{[{niveau.id}]}"
              ng-repeat="niveau in niveaux"
              ng-selected="niveau.id == ecole.niveauid">
              {[{niveau.libelle}]}
      </option>
 </select>

And it works really great.

Now I need to retrieve the selected value and pass it to a function of my controller. So I added :

<select class="form-control"
          ng-model="niveau"
          ng-change="reload(niveau)">

          <option value="{[{niveau.id}]}"
                  ng-repeat="niveau in niveaux"
                  ng-selected="niveau.id == ecole.niveauid">
                  {[{niveau.libelle}]}</option>
</select>

In my controller, I've :

 $scope.reload = function (item) {
        console.log(item);
    }

  $scope.niveaux = [
        {
            "id": 1,
            "libelle": "level1"
        },
        {
            "id": 2,
            "libelle": "level2"
        },
        {
            "id": 3,
            "libelle": "level3"
        }];
 $scope.ecole.niveauid = 3;

Everything work, but I don't have my default value anymore. Please how can I set a default value and retrieved the changed value based on $scope controller ?


Solution

  • Create a selected value object on your controller's scope and set id property on this object after niveaux is set.

    $scope.niveaux = [
        {
            "id": 1,
            "libelle": "level1"
        },
        {
            "id": 2,
            "libelle": "level2"
        },
        {
            "id": 3,
            "libelle": "level3"
        }];
    
    $scope.selectedValue = {id: "2"};  //selected value onload (pass your selected value here)
    
    $scope.reload = function (){
        var selectedId = $scope.selectedValue.id;
        //do something
    }
    

    Then in your HTML, you just need to update your binding. You don't need to specify the ng-selected anymore since it will automatically bind ng-model with option value value="{[{niveau.id}]}". You just need to set the selected property once after loading niveaux list.

    <select class="form-control"
              ng-model="selectedValue.id"
              ng-change="reload()">
    
              <option value="{[{niveau.id}]}"
                      ng-repeat="niveau in niveaux">
                      {[{niveau.libelle}]}</option>
    </select>