![](/img/trans.png)
[英]How to get selected option value of dropdown in angularjs and change the div id dynamically onchange of dropdown
[英]how to add dynamic id on div based on the value of selected option of dropdown in angularjs onchange
在這里我有選擇框,下拉列表的更改,我需要基於下拉列表的選定選項的值在div上添加動態id。我在警報中提到要添加onchange的id。這是下面的代碼
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div id=""></div>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.update = function() {
if($scope.x == 'city'){
alert('add id as city1 inside ablove div');
}
if($scope.x == 'state'){
alert('add id as mystate inside ablove div');
}
if($scope.x == 'country'){
alert('add id as mycountry inside ablove div');
}
}
});
您可以在HTML中執行此操作:
<div id="{{id}}"></div>
您可以在update()
函數中執行此操作:
$scope.update = function() {
if($scope.x == 'city'){
$scope.id = 'city1';
}
if($scope.x == 'state'){
$scope.id = 'mystate';
}
if($scope.x == 'country'){
$scope.id = 'mycountry';
}
}
var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) { $scope.update = function() { if ($scope.x == 'city') { $scope.selectedValue = 'cityName'; } else if ($scope.x == 'state') { $scope.selectedValue = 'stateName'; } else if ($scope.x == 'country') { $scope.selectedValue = 'countryName'; } else { $scope.selectedValue = ''; } } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> <select class="change" ng-model="x" ng-change="update()"> <option value="">Please Select</option> <option value="city">Cities</option> <option value="state">States</option> <option value="country">Countries</option> </select> <span ng-if="selectedValue">You have selected :- {{selectedValue}}</span> </div>
you need to use ngChange and pass ngModel object as argument to your ngChange function
**Example:**
<div ng-app="App" >
<div ng-controller="ctrl">
<select ng-model="blisterPackTemplateSelected" ng-change="changedValue(blisterPackTemplateSelected)"
data-ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates">
<option value="">Select Account</option>
</select>
{{itemList}}
</div>
</div>
js:
function ctrl($scope) {
$scope.itemList = [];
$scope.blisterPackTemplates = [{id:1,name:"a"},{id:2,name:"b"},{id:3,name:"c"}];
$scope.changedValue = function(item) {
$scope.itemList.push(item.name);
}
}
Live example: http://jsfiddle.net/choroshin/9w5XT/4/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.