Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

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.

share|improve this question
up vote 5 down vote accepted

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/

share|improve this answer
    
Good explanation, thanks! I had a feeling that using the ng-options directive would solve it. – jlim Jan 30 '14 at 18:21
    
Can you throw more light on the CDATA part..thanks.. – user1776573 Sep 8 '15 at 7:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.