Open In App

What is the best way to conditionally apply attributes in AngularJS?

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the AngularJS application, the best way to conditionally apply attributes to the elements mostly relies on the specific requirement and the actual nature of the attribute that we need to change. Mostly, considering the use cases, we can use the two common approaches for conditional attribute application by using the ng-if and ng-class directive and also the ng-disabled and ng-class to disable the elements conditionally. In this article, we will see both of the approaches with their implementation in terms of examples to conditionally apply attributes in AngularJS.

Steps to Conditionally Apply Attributes in AngularJS

The below steps will be followed to conditionally apply attributes in AngularJS Applications.

Step 1: Create a new folder for the project. We are using the VSCode IDE to execute the command in the integrated terminal of VSCode.

mkdir condition-attr
cd condition-attr

Step 2: Create the index.html file in the newly created folder, we will have all our logic and styling code in this file. We can also create separate files for HTML, CSS, and JS (if needed).

We will understand the above concept with the help of suitable approaches & will understand its implementation through the illustration.

Using ng-if and ng-class Directives

In this approach, we have conditionally applied the attributes and the styles using the “ng-if” and “ng-class” directives. Here in this example, the ng-if directive is used to dynamically add or remove the elements from the DOM based on the conditions. Also, this allows us to display an input field or edit a text when in edit mode. The “ng-class” directive is used to apply the CSS classes based on the values of specific item properties and mark the tasks completed or high-priority, etc. There is a user-defined function that is used to determine if the task’s due date is in the past. Overall, this approach is used to conditionally apply the attributes along with the styling of elements based on the conditions.

Example: Below is an example that demonstrates conditionally applying attributes in AngularJS using ng-if and ng-class.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <script src=
      </script>
    <style>
        .header {
            text-align: center;
        }
  
        .header h1 {
            font-size: 36px;
            color: green;
        }
  
        .item {
            margin: 10px;
            padding: 10px;
            border: 1px solid #ccc;
            background-color: #f8f8f8;
            border-radius: 5px;
            box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
        }
  
        .completed {
            background-color: #a5d6a7;
        }
  
        .high-priority {
            border: 2px solid #ff6347;
        }
  
        .overdue {
            background-color: #ff7f50;
        }
  
        .item h3 {
            font-size: 20px;
            margin: 0;
            padding: 0;
        }
  
        .item p {
            font-size: 16px;
            margin: 0;
            padding: 0;
        }
  
        .button-container {
            display: flex;
            justify-content: space-between;
        }
  
        .button-container button {
            background-color: #3498db;
            color: #fff;
            padding: 8px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            margin-right: 5px;
        }
  
        .button-container button:hover {
            background-color: #2577a4;
        }
    </style>
</head>
  
<body ng-controller="MyController">
    <div class="header">
        <h1>GeeksforGeeks</h1>
        <h3>
              Approach 1: Using ng-if and ng-class
          </h3>
    </div>
    <div ng-repeat="item in items" 
         ng-class="{
            'completed': item.completed,
            'high-priority': item.priority,
            'overdue': isOverdue(item.dueDate)}">
        <div class="item">
            <h3>
                <span ng-if="!item.editing">
                      {{ item.title }}
                  </span>
                <input ng-if="item.editing" 
                       ng-model="item.title" 
                       ng-blur="saveTask(item)"
                       ng-keyup="$event.keyCode == 13 && saveTask(item)" />
            </h3>
            <p>
                  Status: 
                  {{ item.completed ? 'Completed' : 'Not Completed' }}
              </p>
            <p>
                  Due Date: {{ item.dueDate | date:'mediumDate' }}
              </p>
            <div class="button-container">
                <button ng-if="!item.completed" 
                        ng-click="toggleStatus(item)">
                      Complete
                  </button>
                <button ng-if="item.completed" 
                        ng-click="toggleStatus(item)">
                      Undo
                  </button>
                <button ng-click="editTask(item)">
                      Edit
                  </button>
            </div>
        </div>
    </div>
  
    <script>
        var app = angular.module('myApp', []);
        app.controller('MyController', function ($scope) {
            $scope.items = [
                { title: 'Task 1', 
                  completed: false,
                  priority: false, 
                  dueDate: new Date(2023, 10, 20), 
                  editing: false 
                },
                { title: 'Task 2', 
                  completed: true, 
                  priority: true, 
                  dueDate: new Date(2023, 10, 18), 
                  editing: false 
                },
                { title: 'Task 3', 
                  completed: false, 
                  priority: false, 
                  dueDate: new Date(2023, 10, 22), 
                  editing: false 
                },
            ];
            $scope.toggleStatus = function (item) {
                item.completed = !item.completed;
            };
            $scope.editTask = function (item) {
                item.editing = true;
            };
            $scope.saveTask = function (item) {
                item.editing = false;
            };
            $scope.isOverdue = function (dueDate) {
                const today = new Date();
                return dueDate < today;
            };
        });
    </script>
</body>
  
</html>


Output:

condition1

Using ng-disabled and ng-class Directives

In this approach, we will consider the use case or scenario-based conditions where there is a need to disable the elements using the conditions. So in this case, we can use the ng-disabled and ng-class directives. Here, the ng-disabled is used for form inputs to manage the dynamic behavior for enabling and disabling based on the value of the “disabled” variable. The ng-class is used to provide dynamic styling based on the state of the form elements. In this example, when the user clicks on the “Disable Form” button, the conditions are triggered and the input form elements are been disabled preventing users from entering the data. Once again when the user clicks on the button, the forms are enabled to enter the data. So, this approach mainly makes sure that the form’s attributes are properly managed based on the conditions.

Example: Below is an example that demonstrates conditionally applying attributes in AngularJS using ng-disabled and ng-class Directives.

HTML




<!DOCTYPE html>
<html ng-app="myApp">
  
<head>
    <script src=
      </script>
    <style>
        h1, h3 {
            color: green;
            text-align: center;
        }
  
        .form-container {
            max-width: 400px;
            margin: 0 auto;
            background-color: #f2f2f2;
            padding: 20px;
            border: 1px solid #ccc;
        }
  
        .form-label {
            display: block;
            margin-top: 10px;
            color: #333;
        }
  
        .disabled-input {
            background-color: #ccc;
            cursor: not-allowed;
        }
  
        .info-message {
            margin-top: 10px;
            padding: 10px;
            background-color: #f2f2f2;
            border: 1px solid #ccc;
        }
    </style>
</head>
  
<body>
    <div ng-controller="MyController">
        <h1>GeeksforGeeks</h1>
        <h3>
              Approach 2: Using ng-disabled 
            and ng-class Directives
          </h3>
        <div class="form-container">
            <h2>User Form</h2>
            <form name="myForm" 
                  ng-submit="submitForm()" novalidate>
                <label for="name" 
                       class="form-label">
                      Name:
                  </label>
                <input type="text" 
                       id="name" 
                       name="name" 
                       ng-model="formData.name" 
                       ng-disabled="isDisabled"
                       ng-class="{'disabled-input': isDisabled}">
                <br>
                <label for="email" 
                       class="form-label">
                      Email:
                  </label>
                <input type="email" 
                       id="email" 
                       name="email" 
                       ng-model="formData.email" 
                       ng-disabled="isDisabled"
                       ng-class="{'disabled-input': isDisabled}">
                <br>
                <label for="message"
                       class="form-label">
                      Message:
                  </label>
                <textarea id="message" 
                          name="message"
                          ng-model="formData.message" 
                          ng-disabled="isDisabled"
                          ng-class="{'disabled-input': isDisabled}">
                  </textarea>
                <br>
                <button ng-click="toggleDisabled()">
                      {{ isDisabled ? 'Enable Form' : 'Disable Form' }}
                  </button>
                <button type="submit" 
                        ng-disabled="isDisabled" 
                        ng-click="formSubmitted()">
                      Submit Form
                  </button>
            </form>
            <div ng-show="formDataSubmitted" 
                 class="info-message">
                <h3>Form Data Submitted:</h3>
                <p class="form-label">
                      Name: {{ formData.name }}
                  </p>
                <p class="form-label">
                      Email: {{ formData.email }}
                  </p>
                <p class="form-label">
                      Message: {{ formData.message }}
                  </p>
            </div>
        </div>
    </div>
    
    <script>
        var app = angular.module('myApp', []);
        app.controller('MyController', function ($scope) {
            $scope.isDisabled = false;
            $scope.formData = {};
            $scope.formDataSubmitted = false;
            $scope.toggleDisabled = function () {
                $scope.isDisabled = !$scope.isDisabled;
            };
            $scope.formSubmitted = function () {
                $scope.formDataSubmitted = true;
                alert('Form Submitted!');
            };
        });
    </script>
</body>
  
</html>


Output:

condition2



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads