PTN
PTN

Reputation: 1692

ng-model is not updated when ng-options changes AngularJS

My optionType is not getting updated when I change the value in the dropdown.

<select ng-model="optionType" ng-options="op.option for op in ops" ng-change="optionChanged()"></select>

I use ng-change to check for the value change. I put a break point at the top of optionChanged() and see that the value of optionType is not changed when the function is called.

.controller('uploadCtrl', function($scope) {
    $scope.ops = [ 
        { option: "Report" }, 
        { option: "Support" }, 
        { option: "Learn" } 
    ] ;

    $scope.optionType = $scope.ops[0];

    $scope.optionChanged = function() {

    };
})

Upvotes: 0

Views: 71

Answers (3)

Danny Mencos
Danny Mencos

Reputation: 1295

I believe it's a scope issue. Either bind with $parent, like this: ng-model="$parent.optionType", or put your variable within an object:

JS:

$scope.option = { optionType: $scope.ops[0] };

HTML:

<select ng-model="option.optionType" ng-options="op.option for op in ops" ng-change="optionChanged()"></select>

Source: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Upvotes: 1

LJ.Wizard
LJ.Wizard

Reputation: 605

Try using ng-selected:

HTML

<select ng-model="optionType" ng-options="op.option for op in ops" ng-selected="optionSelected(optionType)"></select>

JS

.controller('uploadCtrl', function($scope) {
    $scope.ops = [ 
        { option: "Report" }, 
        { option: "Support" }, 
        { option: "Learn" } 
    ] ;

    $scope.optionType = $scope.ops[0];

    $scope.optionSelected = function(option) {
          $scope.optionType = option;
          //if the above doesn't work, tell me your console values
          console.log($scope.optionType); //or
          alert($scope.optionType);
    };
})

Upvotes: 1

Paresh Gami
Paresh Gami

Reputation: 4782

Try following it will print selected value in console

$scope.optionChanged = function() 
{
    console.log($scope.optionType.option);
};

Upvotes: 1

Related Questions