5

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.

1 Answer 1

7

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Good explanation, thanks! I had a feeling that using the ng-options directive would solve it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.