Weird behavior ionic in select, ng-model won't update

Ariel picture Ariel · Jul 14, 2015 · Viewed 7.4k times · Source

I'm experiencing something weird, this example works in codepen but won't work in my Ionic app.

When I change the option in the select tag I want to show the selected value, but it won't work, it shows undefined, i've tried in many ways.

This is not the original code, the original one retrieves the values from an external API and populates the options with ngOptions (which works, it populates ok). But it won't update the value in the controller.

So I decided to make it more simple, and it still won't work:

HTML

<select ng-model="optionSelected" ng-change="selectUpdated()">
    <option value="">Select an option</option>
    <option value="h">Hello</option>
    <option value="b">Bye</option>
</select>

JAVASCRIPT

$scope.selectUpdated = function() {
    console.log('Updated');
    console.log($scope.optionSelected);
};

I don't think more code is needed, the HTML is contained in ion-view and ion-content. No errors are shown, only the 'Updated' output and undefined.

When changing the option, I get undefined. But this same code in codepen works just fine.. http://codepen.io/anon/pen/YXvYmq

Can someone tell me what can be happening that triggers this odd behavior?

Thanks in advance.

Answer

Ariel picture Ariel · Jul 14, 2015

Found the solution, pass the ngModel property as a parameter in the ngChange.

HTML

<select ng-model="optionSelected" ng-change="selectUpdated(optionSelected)">
    <option value="">Select an option</option>
    <option value="h">Hello</option>
    <option value="b">Bye</option>
</select>

JS

$scope.selectUpdated = function(optionSelected) {
    console.log('Updated');
    console.log(optionSelected);
};