6

Q. Why my drop down is not showing the selcted value ? Here is the javascript code that i have

<div ng-app="myApp">
 <div ng-controller="MyCtrl">
     <select ng-model="myModel.Active" convert-to-number>
       <option value="-1">Select</option>
       <option value="1">Yes</option>
       <option value="2">No</option>
       <option value="3">Maybe</option>
     </select>
     <span>{{myModel.Active}}</span>
 </div>
</div>

The javascript

var myApp = angular.module("myApp",[]);
myApp.controller("MyCtrl", function($scope){
      $scope.myModel = {};
      $scope.myModel.Active=2; // 

});

The js-fiddle link -- https://jsfiddle.net/shatherali/4mxwzL5y/19/

Edit: Please note i dont want to use string value. Active has to be a number value.

GG.
  • 21,083
  • 14
  • 84
  • 130
ATHER
  • 3,254
  • 5
  • 40
  • 63
  • The `convert-to-number` from http://stackoverflow.com/a/34114258/652669 doesn't work? – GG. Apr 19 '16 at 22:29
  • Not for me atleast, may be i am doing wrong something that i cannot figure out. I updated fiddle with convert-to-number – ATHER Apr 19 '16 at 22:32
  • See my answer, I linked a demo with `convert-to-number` which works fine. Hope it would help you – GG. Apr 19 '16 at 22:37

1 Answers1

3

This solves your issue:

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
      $scope.myModel = {};
      $scope.myModel.Active = '2'; // it's a string
});

DEMO


The convert-to-number directive works fine.

var myApp = angular.module('myApp', []);

myApp.directive('convertToNumber', function () {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function(val) {
                return parseInt(val, 10);
            });
            ngModel.$formatters.push(function(val) {
                return '' + val;
            });
        }
    };
});

DEMO

GG.
  • 21,083
  • 14
  • 84
  • 130
  • Thanks, i just update my question, i cannot change the value to string, it has to stay number – ATHER Apr 19 '16 at 22:26
  • So basically the solution is either use the string value or create your own directive to take use that value ( just like you did ), any idea why built in convert-to-number directive not working ? – ATHER Apr 19 '16 at 22:44
  • 1
    That's not a built-in directive! :) Actually they make their `select` directive to be used with the `ng-options` attribute. They should have done an `option` directive to override the default one but they didn't, so you have to use string values or to "hack" it. :/ – GG. Apr 19 '16 at 22:48
  • Ahhh my bad, actually i did look at the code example at the botton of the angular select documentation page, but never paid attention to the plunker code and thought that its a built in directive. Thanks again. https://docs.angularjs.org/api/ng/directive/select – ATHER Apr 19 '16 at 22:55