Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS select with hard coded options

Tags:

angularjs

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.

like image 553
ATHER Avatar asked Oct 18 '22 11:10

ATHER


1 Answers

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

like image 126
GG. Avatar answered Oct 21 '22 05:10

GG.