AngularJS选择硬编码选项

时间:2016-04-19 22:22:04

标签: angularjs

问。为什么我的下拉菜单没有显示所选择的值? 这是我的javascript代码

<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链接 - https://jsfiddle.net/shatherali/4mxwzL5y/19/

编辑:请注意我不想使用字符串值。活动必须是数字值。

1 个答案:

答案 0 :(得分:3)

这解决了您的问题:

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

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

DEMO

convert-to-number指令正常工作。

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