【问题标题】:Not able to get label from selected option Angular JS无法从选定的选项 Angular JS 中获取标签
【发布时间】:2018-12-14 13:40:44
【问题描述】:

我有一个选择框,我使用一个角度对象作为值,即

{identityName:'Passport',identityId:1}

 <select name="identityProof" ng-model="identityProof" ng-change="changeProofOfIdentity()" ng-options="identity as identity.identityName for identity in identityProofList track by identity.identityId"  id="identityProofList"  class="form-control" data-placeholder="" size="1"></select>

我已经完成了这个设置,所以我可以在 ng-onchange 函数中获取身份 ID 和身份标签。 如您所见,我使用了track by identity.identityId 我只想通过identityId 选择该选项,只有我这样做了

$scope.identityProof = {identityId:userDetails.identityId,identityName:""}; 

现在选择了具有给定值的选项,但是当我尝试获取 $scope.identityProof 即选择框值时,我只得到了 identityId,而不是 identityName,因为我可以看到选择的选项同时具有名称和价值观,
我怎样才能两者兼得?
我是否需要通过获取所选值的标签并将其作为 identityName 传递来使用 jquery 或 javascript 来管理它?
或者有一个选项可以让我重新加载所选对象以同时具有这两个值?

【问题讨论】:

  • ng-options 的文档中所述,>“在同一表达式中使用select astrack by 时要小心。”您真的根本不需要 ng-options 子句中的 identity as 部分,它可能会导致某些情况下,选择根本没有任何价值。

标签: angularjs


【解决方案1】:

您可以使用简单选择来代替ng-option。请参阅以下示例并告诉我。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<select name="identityProof" ng-model="identityProof"  size="1">
  <option ng-repeat="identity in identityProofList" value="{{identity}}">
  {{identity.identityName}}
  </option>
</select>
<span ng-if="identityProof">Selected value = {{identityProof}}</span>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.identityProofList = [{'identityName':'Passport','identityId':1}];
});
</script>
</body>
</html>

【讨论】:

  • 根据 AngularJS,为什么应该使用 ng-option 而不是 ng-repeat : 1. 通过 select 作为理解表达式的一部分分配
猜你喜欢
  • 2014-05-17
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多