What is the best way to activate DOM manipulation once a partial view has been loaded in AngularJS?

What is the best approach to manipulate the DOM after a partial view loads in AngularJS?

If I were using jQuery, I could utilize

$(document).ready(function(){
    // do stuff here
}

However, with Angular, specifically when working with partial views, how can this be achieved? As an example, consider the following simple non-interactive Angular app (with HTML and JS on the same page source):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Angular Question</title>
</head>
<body data-ng-app="demoApp">
    <div data-ng-view=""></div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script>
        var app = angular.module('demoApp', []);

        var controller = {
            demoController: function ($scope, demoFactory) {
                $scope.fruits = demoFactory.getFruits();
            }
        };

        var factory = {
            demoFactory: function () {
                var fruits = ['apples', 'bananas', 'cherries'];
                var factory = {
                    getFruits: function () {
                        return fruits;
                    }
                };
                return factory;
            }
        }

        function appRoute($routeProvider) {
            $routeProvider
                .when('/step-1',
                    {
                        controller: 'demoController',
                        templateUrl: 'partial.html'
                    })
                .otherwise({ redirectTo: '/step-1' });
        };


        app.config(appRoute);
        app.factory(factory);
        app.controller(controller);

    </script>
</body>
</html>

This app includes the following partial:

<ul>
    <li data-ng-repeat="fruit in fruits">{{fruit}}</li>
</ul>

In this scenario, if I wanted to apply a "active" class to the first list item after the partial view finishes loading, how would I achieve this?

Answer №1

Instead of focusing on manipulating the DOM, consider shifting your perspective. The active element is not necessarily the first LI, but rather the first fruit that has been chosen.

To start, introduce the concept of a selected fruit:

var fruits = [
  { name: 'apples', active: true },
  { name: 'bananas', active: false },
  { name: 'cherries', active: false }
]

Next, incorporate this attribute using ng-class in your Angular template:

<ul>
    <li data-ng-repeat="fruit in fruits" ng-class="{ active: fruit.active }">{{fruit.name}}</li>
</ul>

Now you have the flexibility to update your fruits array and modify which fruit is selected, like so:

$scope.fruits[2].active = true;

Answer №2

AngularJS utilizes a model-driven approach. To modify the DOM, simply adjust the data instead.

You have the option to utilize the $first property to activate the first item in the repeater.

<ul>
    <li ng-class="{active : $first}" data-ng-repeat="fruit in fruits">{{fruit}}</li>
</ul>

Alternatively, if you wish to manually activate any item within the repeater by clicking on it, you can change the activate field within the model object.

<ul>
    <li ng-class="{true: 'active', false: ''}[fruit.active]" ng-repeat="fruit in fruits" ng-click="activate(fruit)">{{fruit.name}}</li>
</ul>

Make use of this specific data structure

var factory = {
    demoFactory: function () {
        var fruits = [{
            name: 'apples',
            active: true
        }, {
            name: 'bananas',
            active: false
        }, {
            name: 'cherries',
            active: false
        }]
        var factory = {
            getFruits: function () {
                return fruits;
            }
        };
        return factory;
    }
}

Include the following code in the controller.

$scope.activate = function (fruit) {
    console.log(fruit)
    fruit.active = true;
}

DEMO

Answer №3

To ensure each element has the active property set, you can add it to the model and check for its presence in every element.

var controller = {
    demoController: function ($scope, demoFactory) {
        $scope.fruits = demoFactory.getFruits();
        $scope.fruits[0].isActive = true; // somewhat of a workaround
    }
};

<ul>
    <li data-ng-repeat="fruit in fruits" ng-class="{ active: fruit.isActive }}">{{fruit}}</li>
</ul>

While this approach may not be ideal, especially with AngularJS, it is always recommended to update the model directly to maintain a single definitive representation of your application's state.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Moving Angularjs table rows to another tableMoving table row from one Angular

I need a solution for transferring rows from one table to another. Here are the two tables involved: First Table: <table> <tr ng-repeat="row in items"> <td>{{row.PRODUCTDESCRIPTION}}</td> <td><inpu ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Converting SQL database tables into MVC webpages using JavaScript

Currently, I am working on populating an MVC webpage by utilizing a Controller and a View using C#, HTML, and Javascript exclusively. It is crucial that I avoid using a model or PHP due to the existing format in use. Thus far, all the data has been succes ...

Finding the average JSON value using d3.js

Here is the structure of a JSON file I am working with: [ {"id":1,"sex":"Female","programming":5, "project":7}, {"id":2,"sex":"Male","programming":8, "project":4}, {"id":3,"sex":"Female","programming":5, "project":6}, {"id":4,"sex":"Male","programm ...

Leveraging jQuery to Avoid Memory Leaks

After utilizing jQuery for a couple of months and delving into Javascript memory leaks for several days, I have two concerns related to memory leaks and jQuery: When I bind events (using .bind()) in jQuery, do I need to unbind them (.unbind()) before l ...

Inject the contents of an HTML file into a Vue div

Currently, I am utilizing jsfiddle to go through THIS {{respondedText}} <div>{{respondedText}}</div> But let's say I want to import HTML content from a file or website and then place it inside that div instead of showing "Event Rec ...

Creating a webpage that automatically clicks on a specific category from a selection using JavaScript and CSS

My latest project involves a page filled with divs, each containing specific text content. Located at the top of the page are buttons that enable filtering of the displayed divs based on their data-category. For instance, I have arranged divs showcasing al ...

"Exploring the ThreeJS library's ability to rotate objects within

I have a collection of individual objects in an Array that I want to rotate as a single object. Here is an example: //retrieve body parts from the console bodyParts //Result [THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.Mesh, THREE.M ...

Analyzing string values in Cypress

When attempting to compare two values within a page and make an assertion, my goal is to retrieve the value of one text element and compare it with another value on the same page. While I find this process straightforward in Java/selenium, achieving the ...

Invoke a codebehind function using jQuery

I am encountering an issue while trying to complete a simple task. I am attempting to pass values to a code behind method, perform some calculations, and then return the result. Initially, I started with a test method but have not been successful in making ...

Angular is not defined upon the initial page load

When loading for the first time, Angular is undefined. However, upon refreshing the page for the second time, it works fine. It could possibly be due to JavaScript loading issues. Please take a look at: requirejs([ "js/jquery-1.11.3.min", "js/ang ...

Generating an array in Javascript using JSON

I've been doing a lot of research, but I can't seem to find a solution that works for me. My goal is to retrieve the next four bus arrival times for a specific bus stop using an application that reaches out to an API returning JSON data. The issu ...

The data stored in LocalStorage disappears when the page is refreshed

I'm facing an issue with the getItem method in my localStorage within my React Form. I have added an onChange attribute: <div className = 'InputForm' onChange={save_data}> I have found the setItem function to save the data. Here is ...

Encountering difficulties accessing Node.JS Sessions

Hey there, I am currently working on integrating an angular application with Node.js as the backend. I have set up sessions in Angular JS and created my own factory for managing this. Additionally, I am utilizing socket.io in my Node.js server and handling ...

Finding specific class HTMLElements in TypeScript: A guide to iterating through them

I'm facing a challenge in TypeScript where I need to loop through all HTML elements with a specific class name. My initial attempt was: let elements = [...document.getElementsByClassName("myclass")]; However, I encountered this error messag ...

Locate the midpoint index of the initial sequence occurrence within an array

I am trying to determine the midpoint of the first sequence that appears when given multiple strings in a large array For example: var array = ["c6dafc", "c6dafc", "1d2129", "1d2129", "1d2129", "cfcfff", "cfcfff", "ffffff", "1d2129", "1d2129", "1d2129", ...

Updating input field value with JavaScript

I am working with two textboxes <input id='random_value' name='random_name' value='First' <input id='random_value' name='random_name' value='' My challenge is to replace the value of a tex ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

Ways to detect scrolling activity on the v-data-table module?

Are you looking for a way to detect scrolling events on the v-data-table component in Vuetify framework? I am referring to the scenario where the table has a fixed height, causing the table body to scroll. <v-data-table fixed-header :height=400 : ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...