Retrieve content from ng-include in HTML

I have a piece of html code that is incorporated into multiple html files, each controlled by different controllers. I need to be able to access elements from this included html using their ids in every controller. Below is the html snippet that is included in each file:

<ul class="nav menu" >
    <li id="tom_nav_bar"><a href="/#tom">
        <svg class="glyph stroked dashboard-dial">
            <use xlink:href="#stroked-dashboard-dial"></use>
        </svg>
        BEX Dashboard</a></li>
    <li id="sonar_nav_bar"><a href="#/sonar">
        <svg class="glyph stroked chevron right">
            <use xlink:href="#stroked-chevron-right"/>
        </svg>
        Sonar</a></li>
    <li id="teamcity_nav_bar"><a href="/#teamcity">
        <svg class="glyph stroked chevron right">
            <use xlink:href="#stroked-chevron-right"/>
        </svg>
        TeamCity</a></li>
    <li id="kpi_definitions_nav_bar"><a href="#/kpi_definitions">
        <svg class="glyph stroked chevron right">
            <use xlink:href="#stroked-chevron-right"/>
        </svg>
        Kpi Definitions</a></li>
    <li id="credit_risk_custom_report_nav_bar"><a href="#/department_custom_report">
        <svg class="glyph stroked chevron right">
            <use xlink:href="#stroked-chevron-right"/>
        </svg>
        CREDITRISK Custom Report (beta)</a></li>
</ul>

Let's refer to this code as 'navbar.html'. Now let's take a look at one of the 4 html files where this code is included:

<div ng-include src="'navbar.html'" class="col-sm-3 col-lg-2 sidebar"></div>

Now, in my controllers, I want to target an element with the id 'tom_nav_bar', but unfortunately, I'm unable to do so:

document.getElementById("tom_nav_bar").className = "active";

The issue here is that getElementById is returning null.

Answer №1

Avoid directly manipulating the DOM within your controllers. This can make testing difficult, refactoring challenging, and create confusion as it combines DOM manipulation with presentation logic.

Instead, consider creating a custom directive called 'insert-navbar' with this template:

<div ng-include src="'navbar.html'" class="col-sm-3 col-lg-2 sidebar"></div>

You can then use this directive in multiple locations by simply adding:

<insert-navbar>

Within the link function of the directive, you can access the element like so:

link: function(scope, element) {
  element[0].querySelector('#tom_nav_bar')
}

Answer №2

It appears that there might be a syntax error in your code. You can refer to the AngularJS documentation for proper usage: https://docs.angularjs.org/api/ng/directive/ngInclude

Another potential issue could be that your partial file has not finished loading when the function is called.

document.getElementById

To resolve this, you can add the following script to your code:

function GetElement(idselector) {
    document.getElementById(idselector).className = "active";
}

Then, use this function in the onload parameter of ng-include when including your navbar:

<div 
    ng-include="navbar.html" 
    [onload=GetElement("tom_nav_bar")]
    class="col-sm-3 col-lg-2 sidebar">
</div>

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

Showcasing all elements of an xml through jquery while implementing a filter

Trying to implement a filter on XML using jQuery. The filtered results are showing based on the condition, but facing difficulty in displaying all XML items when the flag is set to 0; meaning that when the flag is zero, all XML items should be displayed ...

Navigating a stationary div within an overflowing container: Key steps

I've been grappling with this issue for quite some time. I'm in need of a div that remains fixed in position when its parent is scrolled horizontally, yet moves along with the content when scrolled vertically. The key is to ensure that the scroll ...

Having difficulty utilizing upstart for launching a basic node server

My attempt at running a basic node js server on digital ocean is not going smoothly despite successfully following this tutorial in the past. When I execute node server.js, my project loads perfectly on the IP address. However, after setting up with upstar ...

Automatically fill Contact Form 7 dropdown options using data from an ACF field

After using the same old Wordpress contact form plugin, FastSecureContactForm, and custom JavaScript code for years to populate a dropdown list in a contact form with file titles from an ACF field, I decided to rebuild my website. Now, I am using Contact F ...

Acquiring a Set of Data from Props

I'm having trouble retrieving an array of data in JSON format that is passed to a React Component. When I check the console with console.log(props), I see the data structure like this: { props: {data: [[array]]}}. The issue I'm encountering is t ...

The JQuery UI draggable feature allows users to drag elements beyond the specified width limit

I am currently working with two draggable divs and I need to find a way to prevent them from being dragged to the right and down. Here is the CSS and JS code for each draggable div: #the-sheet { position: absolute; margin-left: auto; margin-right: a ...

Alternative names for Firefox's "error console" in different browsers

Are there similar tools to Firefox's "Error console" available in other web browsers? I rely on the error console for identifying JavaScript errors, but I haven't found a straightforward way to view error messages in other browsers like Internet ...

Is it possible to use insertMany to create a new collection instead of adding to an existing one

Looking to include an array of objects into an existing collection. Trying out this code: catModel.insertMany(jsonRow, function(err, videos) { The catModel contains a property called modelName: "Yoga-videos-source". In MongoDB, there is a collection name ...

The array is filled with values, however, there seems to be an issue preventing their access. What could possibly be causing this obstacle

After receiving two string values through a callback function, let's call them a and b, I attempt to store them in an array. However, when I check the array using console.log, it only displays the values if I expand the array by clicking on the arrow ...

Transform the MySQL query to fetch the highest date for each user ID and then convert it into a sequelize query

Below is the MySQL query I'm working with: SELECT a.id, a.name, a.pname, b.skill, date_add(a.end_date, interval 1 DAY) AS available_date FROM (SELECT user.id, concat(user.first_name, " ", user.last_nam ...

The webpage's source code does not display any HTML elements related to Prismic slices

I'm currently using a combination of Prismic and Next.js to build a website and everything is running smoothly. However, when I started optimizing the SEO, I noticed that the page source does not contain the HTML for any Prismic slice, nor does it inc ...

Top strategies for ensuring integrity in your frontend React game and preventing cheating

After creating a typing speed game, I am now looking to set up a backend system that can save user high scores and generate a leaderboard. However, I'm concerned about potential users faking their highscores. How can I ensure the integrity of the lead ...

Unable to retrieve the values from document.getElementById("") or document.getElementById("").innerHtml appears to be malfunctioning

I am currently working on an HTA application that includes multiple <input type="text"> fields for users to input data. My goal is to pass this data to a VBScript for processing. Below is the HTML structure: <div id="tableContent" name="tableCon ...

Implementing Object Value Assignment to an Element Using jQuery

I recently received a set of data via an API request: https://i.stack.imgur.com/YGe2D.jpg In order to display this data as selectable options, I included the following code snippet in my AJAX script: $.each($(value.routes), function(index, route){ $ ...

While using the Android Firefox browser, I noticed that the keyboard is causing my screen to shrink in size

As I work on creating a cross-platform HTML page, I have encountered an issue with text fields on Android smartphones. When I attempt to type in a text box, the keyboard pops up and causes my HTML page to shrink within the viewport. I'm curious to kn ...

Applicable exclusively to the parent list item

I am creating a menu with a submenu that has a varying line-height. Unfortunately, I am struggling to prevent this line-height from impacting the list items in my child (submenu). I attempted using ul.nav > li but it continues to affect the lower menu ...

Can anyone suggest a way to iterate over an object and substitute spaces in the keys?

I need to iterate through a dynamically-created object that contains properties with values. The issue is that the property names in this dynamic object contain spaces, which are not allowed in JavaScript object properties. How can I loop through this ob ...

Combining Ajax Form with Django to handle and display errors in form submissions

I am attempting to save information from a form into my Database using Django and Python for the backend. Below is the HTML form: <form> <center> <div class="container-fluid"> <div class="row"> <div clas ...

Using the input type 'number' will result in null values instead of characters

My goal is to validate a number input field using Angular2: <input type="number" class="form-control" name="foo" id="foo" [min]="0" [max]="42" [(ngModel)]="foo" formControlName="foo"> In Chrome, everything works perfectly because it ignores ...

Ways to retrieve a specific Array[property] within an object?

I am struggling to access a specific property within an array of objects. My goal is to extract the "name" elements from the app catalog array, combine them with the names from the custom array apps.name, and assign the result to a new property in the ques ...