AngularJS choose with hard-coded options

Q. Why is my picture not showing selcted? Here is the javascript code 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> 

javascript

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

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

Edit: Please note: I do not want to use a string value. Asset must be a number.

+5
source share
1 answer

This solves your problem:

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function ($scope) { $scope.myModel = {}; $scope.myModel.Active = '2'; // it 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

+3
source

Source: https://habr.com/ru/post/1247476/


All Articles