DOM Manipulation

In this tutorial about DOM manipulation you will learn how to do things like show/hide elements, enable/disable inputs like textboxes, checkboxes and settings classes on elements. For each of these manipulations AngularJS provides you specific directives to achieve this.

The ng-show directive

To show and hide elements on your page you can simply use the ng-show directive. Depending if the value is set to true or false the element will be shown or hidden.

Example

<p ng-show="true">Here I am!</p>

<p ng-show="false">I'm hidden</p>

Play with example »

The ng-disabled directive

Inputs can be enabled and disabled with the ng-disabled directive. Depending if the value is set to true or false the input will be enabled or disabled.

Example

<p>
  <input type="text" ng-disabled="false" value="You can edit me" />
</p>

<p>
  <input type="text" ng-disabled="true"  value="I'm readonly" />
</p>

Play with example »

The ng-class directive

The ng-class directive allows you to dynamically set one or more css-classes on an element. To do so you have three options. Add an expression

  • returning a class as string or multiple classes delimited by a space
  • returning an array of classes
  • map of classes to boolean

Let’s take an example of the first option. It uses an expression in its most simple form, returning the ‘myclass’-class as a string.

Example

<p ng-class="'myclass'">This text has the myclass applied</p>

Play with example »

The second example show the mapping of classes to boolean. The expression-syntax for this is like:

{<YourClassName>: <BooleanVariable>, <AnotherClassName>: <AnotherBooleanVariable> }.

Depending on the value of the boolean, a class is set or not set. You can also have multiple classes active at the same time! See the following example, demonstrating this.

Example

Set/Unset Class: <input type="checkbox" ng-model="mycheckbox">

<p ng-class="{ myclass: mycheckbox }">This is the sampleclass</p>

Play with example »