获取Angular ng-option下拉列表的选定文本

时间:2015-03-31 14:50:27

标签: javascript html angularjs

我的角度代码中有这个下拉列表:

<div class="btn-group" dropdown>
            <select class="selected_location" ng-options="perlocation.id as perlocation.name for perlocation in locations" ng-model="cleaningServiceLocation">
            <option value="">Please Select Location</option>
            </select> 
    <div>

现在在我的控制器中,我可以轻松地将所选值调用为:

$scope.cleaningServiceLocation 

如何获取文本,或者我的情况下,获取所选位置的名称?

2 个答案:

答案 0 :(得分:5)

您可以将模型(perlocation)设为对象而不是(perlocation.id) -

<select class="selected_location" ng-options="perlocation as perlocation.name for perlocation in locations" ng-model="cleaningServiceLocation">

并将其作为 -

访问
$scope.cleaningServiceLocation.name

答案 1 :(得分:2)

每次值更改时,最简单的方法是遍历locations数组,并从name匹配id的位置抓取$scope.cleaningServiceLocation属性:

$scope.getName = function(id) {
  for (var i = 0; i < $scope.locations.length; i++) {
    if ($scope.locations[i].id == id) {
      return $scope.locations[i].name;
    }
  }

  return "";
}

Try it in a Plunker