Filtering by type
by Matthew Day
HTML
<div ng-app="myApp">
<div ng-controller="ParentCtrl as vm">
<ul class="header">
<li ng-repeat="obj in vm.array | unique: 'type'" ng-click="vm.active(obj.type); vm.highlight = obj.type" class="btn" ng-class="{highlight: vm.highlight == obj.type}">{{obj.type}}</li>
<li ng-click="vm.reset()" class="btn">Reset</li>
</ul>
<ul>
<li ng-show="vm.show(obj.type)" ng-repeat="obj in vm.array">
<span>{{obj.name}}</span>
<span>{{obj.age}}</span>
<span>{{obj.type}}</span>
</li>
</ul>
</div>
</div>
CSS
* {
font-family: 'Arial', sans-serif;
font-size: 12px;
}
.header {
margin: 12px 0 32px;
}
ul {
list-style: none;
}
li {
margin: 6px 0;
}
.btn {
background: rgba(50,50,50,0);
border: 1px solid gray;
border-radius: 4px;
cursor: pointer;
display: inline-block;
margin-right: 12px;
padding: 6px 12px;
text-align: center;
text-transform: uppercase;
transition: all 0.3s ease-in-out;
width: 100px;
}
.btn:hover {
background: rgba(50,50,50,1);
color: white;
}
.btn.highlight {
background: rgba(50,50,50,1);
color: white;
}
span {
display: inline-block;
width: 100px;
}
JavaScript
angular.module('myApp', []);
angular.module('myApp')
.controller('ParentCtrl', function(myService) {
var vm = this;
vm.array = myService.getData();
vm.alert = myService.alert;
vm.active = function(text) {
if(text) {
vm.type = text;
}
}
vm.show = function(text) {
if(!vm.type) {
return true
} else if(vm.type === text) {
return true;
} else {
return false;
}
}
vm.reset = function() {
vm.highlight = false;
vm.type = null;
return true;
}
});
angular.module('myApp')
.service('myService', function() {
var array = [
{
"name": "Joe",
"age": "31",
"type": "friendly"
},
{
"name": "Sally",
"age": "21",
"type": "selfish"
},
{
"name": "Bob",
"age": "29",
"type": "selfish"
},
{
"name": "Victoria",
"age": "36",
"type": "friendly"
},
{
"name": "Edith",
"age": "18",
"type": "friendly"
},
{
"name": "Claude",
"age": "43",
"type": "lazy"
},
{
"name": "James",
"age": "11",
"type": "lazy"
},
{
"name": "Maria",
"age": "67",
"type": "hard-working"
},
{
"name": "Kyle",
"age": "24",
"type": "hard-working"
},
{
"name": "Quinn",
"age": "49",
"type": "lazy"
},
{
"name": "Gisela",
"age": "13",
"type": "lazy"
},
{
"name": "Treena",
"age": "37",
"type": "hard-working"
}
];
return {
getData: function() {
return array;
},
alert: function(text) {
alert(text);
}
}
});
angular.module('myApp')
.filter('unique', function() {
return function(collection, keyname) {
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return...