如何在angularjs中获取下拉列表的选定选项值并在下拉列表更改时动态更改div ID

时间:2019-01-10 19:34:04

标签: javascript html angularjs

我正在使用angularjs。我有一个选择框和来自ng repeat的div。在更改选择框时,我需要动态更改div id。例如如果我的选项选择的值为city,则div id将再次为{{y.city}}。如果我的选项选择的值为state,则div id将为{{y.state}}。只需显示,我将id =“ { {y.state}}”在div中。谁能帮我,这是下面的代码。

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 class="change" ng-model="x" ng-change="update()">
<option vlaue="city">Cities</option>
<option vlaue="state">States</option>
<option vlaue="country">Countries</option>
</select>
<div ng-repeat="y in details" id="{{y.state}}">
{{y.state}}
</div>
</div>

脚本

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
    $scope.details = [{"city":"city1","id":"1","state":"state1","country":"country1"},{"city":"city2","id":"2","state":"state2","country":"country2"},{"city":"city3","id":"3","state":"state3","country":"country3"}];
  console.log($scope.details[0].city);
  $scope.update = function() { 
   if($scope.x == 'city'){
   alert('this is city');
   }
   if($scope.x == 'state'){
   alert('this is state');
   }
   if($scope.x == 'country'){
   alert('this is city');
   }

}
});

1 个答案:

答案 0 :(得分:0)

修正错字vlaue-> value

您的代码将是:

<div ng-repeat="y in details" id="{{ y[x] }}">
    {{y[x]}}
</div>

http://embed.plnkr.co/7W830qHem09Xr8Iw2siG