AngularJS Binding: Dropdown binds string, need number instead

I have a dropdown that allows the user to select a number.

<body ng-app="myApp">
    <div ng-controller="MyCtrl">
        <select ng-model="selectedNum" ng-change="numberSelected()">
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>
            <option value="40">40</option>
            <option value="50">50</option>
        </select>
    </div>
</body>

Back in my controller, I can reference the selected value via $scope.selectedNumber

angular.module('myApp', []).controller('MyCtrl', function($scope) {

    $scope.selectedNum = 10;

    $scope.numberSelected = function(){
        alert(typeof $scope.selectedNum); //alerts string, need this to be a number
    }
});

Working Fiddle

I'm new to angular - coming from jQuery I'm used to explicitly invoking Number($('#mySelect').val()) but in angular the value is bound automatically to the $scope.

My question: is there a way to force $scope.selectedNum to be type number? In my actual project I use the selectedNum to do some calculations. I suppose I can use Number(..) or parseInt(..) in various places but I'm thinking that might get a little repetitive and messy.

Answers


The problem is that te option value is a CDATA in HTML - so it is a string in your code. You may solve your problem if you are using an array of numbers and the ng-options directive:

in you controller you may add:

$scope.nums = [10,20,30,40,50];

and in your view:

<select 
      ng-model="selectedNum" 
      ng-change="numberSelected()" 
      ng-options="n for n in nums">
</select>

now you will got a number in your controller function:

$scope.numberSelected = function(){
   console.log(typeof $scope.selectedNum,    $scope.selectedNum);
}

here is a working fiddle: http://jsfiddle.net/5aHRL/


Need Your Help

sqlite select statement returns "undefined"

angularjs sqlite cordova

I am working on a phonegap application and have the following code:

Spring Error on webhosting - Spring : BeanCreationException : Error creating bean with name

spring jsp spring-mvc web-hosting

I'm trying to upload my web app on eatj site. But I'm getting this error. I tried it in my local and its working perfectly fine and I can't really figure it out what is the error.