我有一个选择下拉列表,并且div来自循环。在这里,当我将下拉选项更改为city时,我的div ID应该更改为一,二,三,分别来自json的details列。再次更改下拉列表时down选项说明,我的div ID应该更改为title1,title2 title3,它来自json的title列。在这里工作正常,但我为每个条件创建了新的div,是否可以在一个div中创建多个条件这是下面的代码。
<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 value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-if="id=='city'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.details}}" >hello</div>
</div>
<div ng-if="id=='state'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.title}}" >hello</div>
</div>
<div ng-if="id=='country'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.name}}" >hello</div>
</div>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [
{
title: 'title1',
name:'name1',
details:'one'
},
{
title: 'title2',
name:'name2',
details:'two'
},
{
title: 'title3',
name:'name2',
details:'three'
}
]
$scope.update = function() {
if($scope.x == 'city'){
$scope.id='city';
}
if($scope.x == 'state'){
$scope.id='state';
}
if($scope.x == 'country'){
$scope.id='country';
}
}
});
答案 0 :(得分:2)
要获得所需的结果,请尝试:
为每个值(城市,州和国家/地区)创建一个attr
,如下所示:
if($scope.x == 'city'){
$scope.id='city';
$scope.attr = 'details';
}
使用{{emp[attr]}}
根据下拉选择显示值:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [{
title: 'title1',
name: 'name1',
details: 'one'
},
{
title: 'title2',
name: 'name2',
details: 'two'
},
{
title: 'title3',
name: 'name2',
details: 'three'
}
]
$scope.update = function() {
if ($scope.x == 'city') {
$scope.id = 'city';
$scope.attr = 'details';
}
if ($scope.x == 'state') {
$scope.id = 'state';
$scope.attr = 'title';
}
if ($scope.x == 'country') {
$scope.id = 'country';
$scope.attr = 'name';
}
}
});
<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 value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-repeat="emp in groups" ng-attr-id="{{emp[attr]}}">{{emp[attr]}}</div>
</div>
</div>
答案 1 :(得分:0)
为此,您可以使用嵌套三元运算符。对于您的情况,它看起来像这样:
<div ng-repeat="emp in groups" ng-attr-id="{{id=='city' ? emp.details : id=='state' ? emp.title : emp.name}}" >hello</div>
我没有在angular 1上实现此功能,但它在angular 2上有效。内置的Angular指令(ngif,ngfor ngclass等)在两个版本中都几乎相同。