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

谁说我不能喝 提交于 2019-12-23 16:33:40

问题


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.


回答1:


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);
};



回答2:


I was having the same problem today and had to create a workaround to use the select normally.

javascript

$scope.updatePreferredLanguageValue = function() {
   $scope.PreferredLanguage = this.PreferredLanguage;
};

html

<select ng-model="PreferredLanguage" ng-options="Language.id as Language.name for Language in LanguageList" id="LanguageListSelect" name="LanguageListSelect" ng-change="updatePreferredLanguageValue()">
</select>

So basically I have a method that is called when the value is changed that makes sure the change is set on the $scope variable. Not pretty but it works.




回答3:


Try to use $parent in your ng-model and call it from your controller.

Example

<select ng-model="$parent.selectedCar">
 <option>...</option>
</select>

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



来源:https://stackoverflow.com/questions/31416169/weird-behavior-ionic-in-select-ng-model-wont-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!