AngularJS: ng-model switching int to string
It gets changed to a string because HTML has no concept of what an integer is. Ultimately the selected variables is read from the DOM and handed to angular and so it changes its type.
You can force the model to always contain an integer with a directive
directive('forceInt', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, controller) {
controller.$parsers.push(function(value) {
if (typeof value === 'string') {
value = parseInt(value, 10);
controller.$setViewValue(value);
controller.$render();
}
return value;
});
}
};
});
(plunk)
But I see someone already pointed out that there might be better ways to keep track of the ordering. FWIW that directive will at least keep making sure the model is never a string.
Eventually I was able to solve this by doing:
<div class='header'>
<select ng-model="item.order" ng-change="changeItemOrder((itemIndex + 1), item.order, itemIndex)">
<option ng-repeat="thing in category.items" ng-selected="(item.order === ($index + 1))" value="{{$index + 1}}">{{$index + 1}}</option>
</select>
</div>
This, and only this solution (so far) has what I want/need. I need the item.order model to keep track of the current position and to show the correct value on initial load. You can't set the model to questionIndex because that disturbs other HTML-elements, I can't set it to $index because that also did weird things.
While the other solutions suggested here 'work', they do not result in the spec that was given to me. So I guess this is kinda specific.