CHApTer 5 ■ DIreCTIveS
// a function, placed into the scope, which
// can toggle the value of the isHidden variable
$scope.showHideColors = function () {
$scope.isHidden = !$scope.isHidden;
}
}
);
It’s surprisingly short, mainly because we don’t actually do very much heavy lifting ourselves. Instead, we
concentrate on managing the state of the isHidden variable. The ngHide directive is taking care of how the underlying
task is actually implemented.
As you may have come to expect by now, we are utilizing the scope object. Consequently, the isHidden variable
and the showHideColors() function can be used in the directives expressions. These two actions constitute the wiring
up of our logic.
Take a look at the following excerpts from the product-detail.html file from Listing 5-1. You can see where the
showHideColors() function that we assigned to the scope is used by ngClick
... and where the isHidden variable we assigned to the scope is used by ngHide
■ Tip Just a reminder: There is no need to specify the $scope object within these Angular expressions, as expressions
are implicitly associated with a scope. Attempting to do, say, "$scope.isHidden" in the above expression would not
work.
Why are all of the color divs hidden by default? This is because the expression, isHidden, provided to the ngHide
directive on each of the divs evaluates to true. What is really cool, due to the live updating that Angular JS performs,
is that anytime the value of isHidden changes, ngHide will respond accordingly. Of course, we want it to change, and
that is why we use the Show Available Colors button along with the ngClick directive.
The button uses the ngClick directive, and the expression we pass to this directive is a call to our
showHideColors() function. It is this function call that will change the state of the isHidden variable, thereby causing
the ngHide directive’s expression now to evaluate to false. Consequently, the color divs become visible.
An interesting requirement in the case of the button is that we want the text to adapt when the button is clicked.
We do this using a particularly helpful technique that can be used within Angular JS expressions. I’m referring to the
following line:
{{isHidden? 'Show Available Colors' : 'Hide Available Colors'}}
This expression uses the ternary conditional operator. It can look a little odd if you haven’t seen it before, but it’s
actually quite easy to use. The first portion, the bit before the? (question mark), must evaluate to true or false. If it
evaluates to true, the statement before the : (colon) is executed; otherwise, the one after it is executed. In our case, the
text appearing on the button will update itself, based on whether or not the color divs are currently hidden, because
we use isHidden to drive the outcome.