AngularJS Selectable Directive
AngularJS directive to make any element "selectable". Uses AngularJS, Twitter Bootstrap, FontAwesome, CSS, and jQuery
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
<div ng-app="app" ng-controller="appCtrl">
<div class="container">
<div class="row">
<span class="page-header"><h3>Click an item</h3></span>
</div>
<h2>
{{activeItem}}
</h2>
<div class="row">
<div ng-repeat="item in items" class="col-xs-4 card" selectable="setActiveItem(item.value)"><i class="fa fa-check fa-inverse fa-lg" ng-show="activeItem == item.value"></i><span ng-hide="activeItem == item.value">{{ item.display }}</span>
</div>
</div>
</div>
</div>
CSS
.card {
border: 1px solid #ccc;
border-radius: 5px;
text-align: center;
padding-top: 20px;
padding-bottom: 20px;
margin: 5px;
cursor: pointer;
}
.active{
background-color: #5cb85c;
}
JavaScript
var mod = angular.module('app', []);
mod.controller('appCtrl', function($scope) {
$scope.activeItem = '';
$scope.items = [
{
display: 'Item 1',
value: 'one'
},
{
display: 'Item 2',
value: 'two'
},
{
display: 'Item 3',
value: 'three'
},
{
display: 'Item 4',
value: 'four'
},
{
display: 'Item 5',
value: 'five'
},
{
display: 'Item 6',
value: 'six'
},
{
display: 'Item 7',
value: 'seven'
},
{
display: 'Item 8',
value: 'eight'
},
{
display: 'Item 9',
value: 'nine'
},
];
$scope.setActiveItem = function(val) {
$scope.activeItem = val;
//alert("Active item is: "+ $scope.activeItem)
};
});
mod.directive('selectable', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind('click', function(e) {
$(".active").each(function() {
$(this).removeClass('active');
});
element.addClass('active');
scope.$apply(attrs.selectable);
});
}
}
});