Reputation: 57
I have an object something like
x=[{a:1,b:2,c:3,d:'A'},{a:3,b:3,c:1,d:'C'},{a:2,b:1,c:2,d:'B'}]
View In HTML there are 3 buttons
<button ng-click="sortbyA()">
<button ng-click="sortbyB()">
<button ng-click="sortbyC()">
And a pop-up
<div ng-repeat='i in x | orderBy:sortBy'>
<table>
<tr><td>{{i.d}}</td></tr>
</table>
</div>
Angular JS Controller:
var app = angular.module("myApp", []);
app.controller("myCtrl", ['$compile', '$http', '$scope', function ($compile, $http, $scope) {
$scope.get_results=function(){
var response= $http.get();
response.success(function(){
$scope.sortBy='a';
});
}
$scope.sortbyA=function(){
$scope.sortBy='a';
}
$scope.sortbyB=function(){
$scope.sortBy='b';
}
$scope.sortbyC=function(){
$scope.sortBy='c';
}
}])
Use case is to populate data of table based different clicks(A,B,C) with their corresponding property in x
Eg: If click on B,table should have data sorted by attribute :b, If click on C,table should have data sorted by attribute :c
Upvotes: 1
Views: 1672
Reputation: 3148
In HTML
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.data = [{ a: 1, b: 2, c: 3, d: 'A' }, { a: 3, b: 3, c: 1, d: 'C' }, { a: 2, b: 1, c: 2, d: 'B' }];
$scope.sortBy = 'a'; //for default sorting
$scope.sortItems = function(key) {
$scope.sortBy = key; // key on which prop you want to sort
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div class="" ng-controller="MainCtrl">
<button ng-click="sortItems('a')">a</button>
<button ng-click="sortItems('b')">b</button>
<button ng-click="sortItems('c')">c</button>
<button ng-click="sortItems('d')">d</button>
<br />
<div ng-repeat='i in data | orderBy:sortBy'>
<table>
<tr>
<td>{{i.a}}</td>
<td>{{i.b}}</td>
<td>{{i.c}}</td>
<td>{{i.d}}</td>
</tr>
</table>
</div>
</div>
</body>
Upvotes: 2
Reputation: 5041
Response data:
x=[{a:1,b:2,c:3,d:'A'},{a:3,b:3,c:1,d:'C'},{a:2,b:1,c:2,d:'B'}]
Your buttons:
<button ng-click="sortBy = 'a'">
<button ng-click="sortBy = 'b'">
<button ng-click="sortBy = 'c'">
Your table:
<div ng-repeat='i in x | orderBy:sortBy'>
<!-- blabla -->
Your js:
var app = angular.module("myApp", []);
app.controller("myCtrl", ['$compile', '$http', '$scope', function ($compile, $http, $scope) {
$scope.sortBy = 'a';
$scope.get_results=function(){
var response= $http.get();
response.success(function(){
//blabla
});
}
}])
Upvotes: 0