Angular: Directive Test
http://angularjs.org/
HTML
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
<div ng-controller="peopleController">
<div ng-repeat="person in people" class="person">
<div class="avatar"><img src="http://placehold.it/60x70"></div>
<div class="header">
<div class="name">{{person.name}}</div>
<div class="status"></div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<div class="caption">
There are {{selectedPeople().length}} people selected.
</div>
</div>
CSS
.person, .caption {
padding: 10px;
margin: 10px;
border-radius: 10px;
border: 1px solid gray;
font-family: helvetica;
}
.selected {
background-color: #F0F5E0;
color: #576516;
}
.name {
float: left;
margin-left: 10px;
}
.header {
width: 450px;
float: left;
}
.avatar {
float: left;
}
.status {
float: right;
}
.clear {
clear: both;
}
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('peopleController', function($scope) {
$scope.people = [
{
name: 'Fred Belcher',
selected: false
},
{
name: 'Tommy Toejam',
selected: false
},
{
name: 'Lily Liverstein',
selected: false
},
{
name: 'Jimmy Jaggov',
selected: false
}
];
$scope.selectedPeople = function() {
return _.where($scope.people, {
selected: true
});
}
});
myApp.directive('person', function() {
return {
restrict: 'C',
link: function(scope, element, attrs) {
element.on('click', function() {
scope.person.selected = !scope.person.selected;
$(this).toggleClass('selected');
});
}
};
});