CHApTer 5 ■ DIreCTIveS
We need a link function that achieves all but one of these requirements. The first requirement is already met,
because the button is defined in the HTML we assigned through the template option. The second requirement is
partially met, but it still needs work. I say partially met, because the template also has the colorContainer div, which
will be the parent container for our color list. This div makes use of the ngHide directive.
Listing 5-9 shows our link function. This function completes the requirements we listed earlier. I will put this in
context with the rest of our custom directive shortly, but for now, see if you can pick out what is happening here.
Listing 5-9. The link Function
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;
}
// DOM manipulation
var colorContainer = $element.find('div');
angular.forEach($scope.$parent.colorsArray, function (color) {
var appendString = "
colorContainer.append(appendString); });
}
The first thing to notice about the link function is that we have access to the element on which the directive
is defined and a scope object (via the $element and $scope arguments accepted by the function). These are
automatically injected into our function by the framework.
The first batch of logic in this function simply sets the default state of the directive such that the color list is
hidden. Next, we attach the showHideColors() function to the scope. The next batch of logic, under the DOM
manipulation comment, is the real meat of the directive.
We want to add div elements dynamically to the colorContainer div, so we create a variable called
colorContainer. To achieve this, we used the following statement:
var colorContainer = $element.find('div');
If you have used jQuery before, this might look familiar. This is because $element is a jQuery wrapped element
and, as such, can use jQuery methods, such as find() and append().
■ Note By default, Angular JS uses jqLite. This is a trimmed-down version of jQuery containing only the most essential
features. If you add a script reference to the full version of jQuery, Angular will automatically use this version instead of
using jqLite. If you are keen to learn what jqLite has to offer, you can do so here: https://docs.angularjs.org/api/
ng/function/angular.element.
With the colorContainer reference in hand, we can now create the color list by attaching to it a div for each color
in the array. We do this by looping through the colors array, using the handy angular.forEach method and, at each
pass, append to build the list of colors.