Angular handles all the mess. Angular makes the process of binding two directives to the same variable quite easy, and therefore simplifies common functionalities. We’ll see examples where two or more directives can be bound together (and therefore effect the appearance of different elements) through a common variable. This would come in handy in many common one-page applications (such as forms) where the element display on the page changes in accordance with user types/choices.
We’ll start by creating a new $scope variable and set its default to true.
$scope.dButton = true;
We’ll go to the HTML and create a button, which will be either disabled or enabled, depending on the value of the $scope variable we have just created in the script:
We’ll enable/disable this button using a checkbox, like so:
<p><input type="checkbox" ng-model="dButton">Disable Button</p>
Again, whether the box is checked or not is dependent on the value of the $scope variable, dButton.
So, in this way of binding the value of the scope variable to both the ng-disabled and ng-model directives, we were able to enable/disable an element to our liking.
Moving on to hiding and showing elements. We’ll start with our example by creating a Boolean $scope variable in our script:
$scope.dayButton = true;
In the HTML, inside our controller, we’ll create another paragraph with another checkbox. We’ll bind ng-model directive to our new dayButton variable.
<p> <input type="checkbox" ng-model="dayButton">Day Time </p>
Now, we’ll create two paragraphs which will be displayed dependent on whether or not the box is checked. For this purpose, we’ll use the directive ng-hide and bind it to the value of dayButton. When the latter is true, ng-hide hides the element. When its value is false, ng-hide shows the element. We can use the “!” expression to convert one Boolean value to another. Like so:
<p ng-hide="!dayButton">Good Day</p> <p ng-hide="dayButton">nighty night</p>
Explanation: If the value of dayButton is false, then the value of ng-hide becomes true and it hides the ‘good day’ paragraph. And vice verse.
If the value of dayButton is true then ng-hide is true, and it hides the ‘nighty night’ paragraph.
Since the checkbox is also tied to the value of dayButton, checking and unchecking the box results in hiding/showing different paragraphs.
In summary, in this tutorial we have seen basic examples of how we can disable/enable, hide/show and dynamically change the classes of elements using AngularJS. The trick is all in the directives which we bind to variables. Two or more directives can be bound together (and therefore effect the appearance of different elements) through a common variable.