Angular Talk: 6 - Directives
http://angularjs.org/
by boneskull
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<!-- body tag has ng-app="myApp" -->
<div ng-cloak>
<div ng-controller="MyCtrl">
<h3>Available Toppings</h3>
<ul ng-repeat="topping in toppings">
<li hover-description="topping.description">{{topping.name | capitalize}} <button ng-click="addTopping(topping)">add topping</button></li>
</ul>
</div>
<br/>
<div ng-controller="SelectedToppingCtrl">
<h3>Selected Toppings</h3><button ng-click="reset()">reset</button>
<ul ng-repeat="topping in selected_toppings">
<li>{{topping.name | capitalize}}</li>
</ul>
</div>
</div>
CSS
li {
display: list-item;
}
h3 {
font-weight: bold;
}
JavaScript
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', 'Toppings', function($scope, Toppings) {
$scope.toppings = [{
name: 'ham',
description: 'tender juicy ham'},
{
name: 'olives',
description: 'ripe california olives'},
{
name: 'anchovies',
description: 'super fishy anchovies'}];
$scope.selected_toppings = Toppings.selected_toppings;
$scope.addTopping = function(topping) {
$scope.selected_toppings.push(topping);
};
}]);
myApp.controller('SelectedToppingCtrl', ['$scope', 'Toppings', function($scope, Toppings) {
$scope.selected_toppings = Toppings.selected_toppings;
$scope.reset = function() {
$scope.selected_toppings = [];
};
}]);
myApp.service('Toppings', function() {
this.selected_toppings = [];
});
myApp.filter('capitalize', function() {
return function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
});
myApp.directive('hoverDescription', ['$compile', '$templateCache', function($compile, $templateCache) {
return function(scope, element, attrib) {
var description = scope.$eval(attrib.hoverDescription);
element.on('mouseenter', function() {
element.append('<pre>' + description + '</pre>');
}).on('mouseleave',function() {
element.children('pre').remove();
});
};
}]);