AngularJS Select上未显示的选定值

时间:2016-11-01 11:47:30

标签: angularjs

我的问题是当我更改下拉菜单的值时,值不会显示在下拉菜单中,但我的控制台中会显示正确的值。不知道为什么它现在还没有工作,因为我在另一个项目中有相同的实现。也许我忽略了一些事情。

  

初始化时我设置了

selected_type = types[0]
// What will result in Type1 being displayed on page load.
  

你可以在这里找到:https://jsfiddle.net/596tzsh8/7/

2 个答案:

答案 0 :(得分:1)

您可以按如下方式更改选择

<select name="type" class="col-xs-12 dropdown-list" ng-model="selected_type" class="col-xs-8" ng-init="selected_type = types[0]" ng-options="type as type.Name for type in types track by type.Id" ng-change="GetValueTypeDropdown()">

你也可以有一个$ scope变量并在ng-change上显示它

$scope.GetValueTypeDropdown = function() {
 console.log($scope.selected);
};

<强> DEMO

答案 1 :(得分:1)

使用:

ng-options="selected_type as selected_type.Name for selected_type in types track by selected_type.Id"
//                 ^
//         the object itself

...而不是:

ng-options="selected_type.Id as selected_type.Name for selected_type in types track by selected_type.Id"
//                  ^
//            the object's ID

然后,在你的回调函数中,替换:

var typeID = this.selected_type;
//                      ^
//              the object itself

... by:

var typeID = this.selected_type.Id;
//                        ^
//                 the object's ID

...而且你已经全部准备好了!

查看您的分叉JSFiddle here,或者使用下面的代码段。

&#13;
&#13;
var app = angular.module("app", ["controllers"])

var controllers = angular.module("controllers",[]);
controllers.controller('myController', function($scope){

	$scope.types = [{
            Id: 1,
            Name: 'Type1'
        }, {
            Id: 2,
            Name: 'Type2'
        }, {
            Id: 3,
            Name: 'Type3'
  }];

  $scope.GetValueTypeDropdown = function () {
  	var typeID = this.selected_type.Id;
    	$scope.the_type = $.grep($scope.types, function (selected_type){
      	return selected_type.Id == typeID;
      })[0].Name;
      console.log($scope.the_type);
    return $scope.the_type;
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="myController">
      <form>
          <select name="type" class="col-xs-12 dropdown-list"
                  ng-model="selected_type" class="col-xs-8"
                  ng-init="selected_type = types[0]"
                  ng-options="selected_type as selected_type.Name for   selected_type in types track by selected_type.Id"
                  ng-change="GetValueTypeDropdown()">
          </select>
      </form>
    </div>
</div>
&#13;
&#13;
&#13;