var app = angular.module('plunker', []);
app.controller('MainCtrl', function() {
var vm = this;
vm.pretty = false;
vm.buttonLabel = 'Make Pretty!';
vm.toggle = function() {
vm.pretty = !vm.pretty;
vm.buttonLabel = vm.pretty ? 'Make Boring' : 'Make Pretty!';
};
});
app.directive('makePretty', function() {
function randomPrettyColour() {
var prettyColours = ['Chartreuse', 'Fuchsia', 'MediumPurple', 'Yellow', 'PeachPuff', 'HotPink', 'FireBrick', 'Aqua', 'DeepSkyBlue', 'Peru', 'NavajoWhite', 'MistyRose'];
return prettyColours[Math.floor(Math.random() * prettyColours.length)]
}
return {
link: function(scope, element, attrs) {
function makeBoring() {
angular.forEach(element, function(el) {
if (el.nodeType === Node.ELEMENT_NODE) {
angular.element(el).css({
'color': '',
'background-color': ''
});
}
});
}
function makePretty() {
angular.forEach(element, function(el) {
if (el.nodeType === Node.ELEMENT_NODE) {
angular.element(el).css({
'color': randomPrettyColour(),
'background-color': randomPrettyColour()
});
}
});
}
scope.$watch(function() {
return attrs.makePretty;
}, function(newVal, oldVal) {
if (newVal !== 'false') {
makePretty();
} else {
makeBoring();
}
});
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.6/angular.js" data-semver="1.2.25"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as vm">
<h1>Make It Pretty!</h1>
<button class="btn btn-default btn-lg" ng-click="vm.toggle()">{{ vm.buttonLabel }}</button>
<p make-pretty-start="{{ vm.pretty }}">'You should learn not to make personal remarks,' Alice said with some severity; 'it's very rude.'</p>
<p>The Hatter opened his eyes very wide on hearing this; but all he SAID was, 'Why is a raven like a writing-desk?'</p>
<p make-pretty-end>'Come, we shall have some fun now!' thought Alice. 'I'm glad they've begun asking riddles.—I believe I can guess that,' she added aloud.</p>
</body>
</html>
/* Put your css in here */
body {
padding: 20px;
}
.btn {
margin-bottom: 10px;
display: block;
}
# Multi-Element Custom Directive
An example to accompany the blog post: http://www.michaelbromley.co.uk/blog/260/writing-multi-element-directives-in-angularjs