我在这里使用angularjs,我的div将基于下拉列表的变化。在这里,我需要根据其值将h4标签限制为仅一次。如果我的值很重要多次出现,则应该再次如果我的值是多次出现的主要值,那么应该只有一次。这些值来自json,所以它是动态的。任何人都可以帮助angularjs的新手,这是下面的代码
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="condition">condition</option>
</select>
<div class="main">
<div ng-repeat="emp in groups" ng-attr-id="{{emp[attr]}}">
<h4 id="test" class="{{emp[attr]}}">{{emp[attr]}}</h4>
</div>
</div>
</div>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [
{
name: 'Malaria',
symptom:'fever',
categoty:'critical',
id:'1'
},
{
name: 'cancer',
symptom:'diesease',
categoty:'critical',
id:'3'
},
{
name: 'fever',
symptom:'diesease',
categoty:'major',
id:'3'
},
{
name: 'Cold',
symptom:'colds',
categoty:'major',
id:'2'
}
]
$scope.update = function() {
if($scope.x == 'condition'){
$scope.id='categoty';
$scope.attr = 'categoty';
}
}
});
答案 0 :(得分:0)
当您说“数据中仅来一次”时,您有点模棱两可。我认为您在共享plnkr中寻找的行为是允许用户选择一个属性并按该属性分组,该属性仅显示各个分组下列出的name属性。
为此,我构建了用户可以选择的属性选择。因此,如果将来将次要属性添加到对象中,它将继续起作用,并且可以将其添加到选择器中。
选择项目后,将对数据进行解析,并按选定的属性对项目进行分组。每个组都是映射到数组(项目名称)的键(选定属性)。分组后,两个ng重复项可以显示其数据。每个组类别的顶级ng-repeat,以及嵌套的ng-repeat,以显示该组下的项目/名称。
var jsonData = [
{
name: 'Malaria',
symptom:'Fever',
category:'Critical',
id:'1'
},
{
name: 'Cancer',
symptom:'Diesease',
category:'Critical',
id:'3'
},
{
name: 'Fever',
symptom:'Diesease',
category:'Major',
id:'3'
},
{
name: 'Cold',
symptom:'Colds',
category:'Major',
id:'2'
}
];
// Setup angular
angular.module('myApp', [])
.controller('MainController', function MainController() {
var self = this;
// Setup your dropdown selections to choose an attribute
self.attrs = [
'category',
'symptom'
];
// On selection change, update how groups is built
self.onSelect = function onSelect(attr) {
// First build a map of all items grouped by attr
var groupMap = {};
jsonData.forEach(function group(item) {
var attrVal = item[attr],
arr = groupMap[attrVal];
if (!arr) {
arr = groupMap[attrVal] = [];
}
// Push the item name
arr.push(item.name);
});
self.groups = groupMap;
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainController as $ctrl">
Select Attribute:
<select ng-model="$ctrl.selectedAttr" ng-change="$ctrl.onSelect($ctrl.selectedAttr)">
<option ng-repeat="attr in $ctrl.attrs">{{::attr}}</option>
</select>
<div ng-show="::$ctrl.selectedAttr">
<div ng-repeat="(attr, names) in $ctrl.groups">
<h4>{{::attr}}</h4>
<ul>
<li ng-repeat="name in names">{{::name}}</li>
</ul>
</div>
</div>
</div>