Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 440
jlim Avatar asked Jan 30 '14 06:01

jlim


1 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/

like image 150
michael Avatar answered Sep 20 '22 17:09

michael