CHApTer 5 ■ DIreCTIveS
return {
restrict: 'AE',
template: "
- "{{isHidden? 'Show Available Colors' : 'Hide Available Colors'}}"
- """,
- "
link: function ($scope, $element) {
// set default state of hide/show
$scope.isHidden = true;
// add function to manage hide/show state
$scope.showHideColors = function () {
$scope.isHidden = !$scope.isHidden;
}
// add colors divs to the document
var colorContainer = $element.find('div');
angular.forEach($scope.colorsArray, function (color) {
var appendString = "
div>";
colorContainer.append(appendString);
});
}
};
});
This is not bad for a first directive—though I think you will agree that there are quite a few steps involved! To keep
things manageable, I set up the background color using an inline style, but you might want to create a style sheet with
a class and use that class here instead. This is certainly much better practice in most cases. Custom directives are a
topic worthy of their own book. Nevertheless, even with this brief introduction, you can build all sorts of reusable logic
and user-interface components. I encourage you to explore this topic further, perhaps using some of the many online
tutorials or the excellent book Pro AngularJS by Adam Freeman (Apress, 2014).
Summary
Directives in AngularJS are very powerful, but it can take some time to understand all of the processes that lie behind
them completely—particularly when it comes to creating custom directives. In this chapter, you had a good first look
at many aspects of directives and, I hope, gained a solid footing on which to base further exploration.
In the next chapter, we will look at another area where AngularJS really shines: HTML forms. While HTML
forms are not an AngularJS feature as such, you will appreciate how much more enjoyable and productive
AngularJS makes them.