Getting an HTML element by its ID that was passed from the ng-init directive in Angular can be achieved

When I use ng-click, I am able to retrieve the html element by id. However, when I use ng-init, I only get null. Please take a look at my codepen here.

HTML Code:

<script type="text/javascript">
    var memId = "bb7de28f-0f89-4f14-8575-d494203acec7";
</script>   

<div ng-app="myapp" ng-controller="MainCtrl" ng-init="getMember(memId)">
    <span id="audio-{{memId}}">
        Your member ID: {{memId}}
    </span>     
    <span ng-click="getMember(memId)"> Click me <span>
</div>

Controller Code:

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.memId = $window.memId;

  $scope.getMember = function(id) {
    console.log(id);
    var voice = document.getElementById('audio-' + id);
    console.log(voice);
  };
}]);

Answer №1

One way to achieve this is by using the angular $timeout function which waits until the Angular cycle is finished and elements are rendered.

Controller:

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', '$timeout', function($scope, $window, $timeout) {
    $scope.memId = $window.memId;
    $scope.getMember = function(id) {

        $timeout(function() {
            console.log(document.querySelector('#audio-' + id))
        });
    };

}]);

Answer №2

It is not recommended to access DOM elements in the ng-init directive as they have not been added to the DOM yet at that point. It's best to avoid direct manipulation of DOM elements in Angular, so you may want to reconsider your code structure.


For proper usage of the ngInit directive, refer to https://docs.angularjs.org/api/ng/directive/ngInit.

ngInit should only be used for specific cases, such as aliasing properties in ngRepeat or injecting data from server side scripting. In most scenarios, it is recommended to use controllers instead of ngInit to initialize values on a scope.

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

React - Highcharts Full Screen dark overlay

I am currently working on integrating highcharts/highstock into my application, and I have encountered an issue with the full screen functionality. The challenge I am facing is setting a fixed height for my charts while also enabling the option to view ea ...

A method for displaying information in HTML by implementing ng-repeat in AngularJS

I have retrieved JSON data in my controller as a response and now I need to display it in the HTML. Here is what I have implemented: Inside my controller: .controller('DataImportControl', ['$scope','$http', '$location& ...

What is the best way to acquire an ID that is generated dynamically?

Being new to javascript and ajax, I am facing a challenge. I have a while loop with 2 buttons, both of which seem to function correctly, except for one small issue... The product-id is only being passed for the first or last element in the loop. How can I ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

Why won't JSZip accept a base64 string for loading a zip file?

As I work on implementing a feature where a small JSON object is written to the URL as a user interacts with items on a page, I also want to make sure the URL can be read later so users can resume where they left off. I successfully managed to create the ...

Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable. Check out Stackblitz export class AppComponent { urls; format; on ...

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

Automatically activate the next tab in Bootstrap

I have a modal that performs a count. Once the count is completed, the modal closes. My goal is to automatically switch to the next tab in Bootstrap when the modal closes. Here is the HTML: <ul class="nav nav-tabs namelocationtable"> <div clas ...

Skipping validation while navigating back on SmartWizardIf you need to bypass validation during backward

Looking for assistance with Jquery smartwizard? Check out the link. I want to disable validation when a user clicks on the "Previous" button in any step, except for the first step where the Previous button is disabled by default. Below is my JavaScript co ...

A guide to efficiently pre-rendering secure APIs on a server for Next.js

Currently, I am working on a project that involves fetching data from multiple pages. However, the challenge lies in the fact that all APIs are secured, except for the initial API that fetches data for the home page. Furthermore, all other APIs are protect ...

Transferring data between modules using Ajax or services in React.js

I have a React application where I need to pass data received in one component to another. After receiving the data successfully, I set the state and then try to pass this data as a property to the next component. However, when I try to access this passed ...

What is the process for attaching an on-click event listener by utilizing an argument that is passed to a function in JavaScript?

These are the functions I have created: function type(message) { document.getElementById("body").innerHTML="<div id=\"textbox\" class=\"textbox\"></div><div id=\"oc\&q ...

I am currently developing an email platform, however the link is hidden in such a manner that it does not lead to the intended destination

I have a piece of code that is supposed to generate a password reset link, but it seems to be producing an incorrect URL. var body = new StringBuilder(); body.Append("A password reset has been requested for your account. "); ...

"Dealing with an unspecified number of fields in an ExtJS data model

I have a data model that is designed to accommodate various incoming data by keeping it generic and allowing for the addition of multiple meta data tags to my project. How can I effectively map these data fields to the Model or access them in the array w ...

Centralize the storage of domain within an AngularJS service

In my Angular service, I have the following method: function send(data) { return $http({ method: 'POST', url: 'https://test.domain/test/send', data: $httpParamSerializerJQLike(data) ...

Employ a unique filter within the controller of your AngularJs directive

Current Situation I currently have an array of users with their information and I am using ng-repeat along with a custom directive to create HTML user cards. The scope for each card is specific to the individual user. Within the user model, there is a v ...

Trigger a JavaScript function upon clicking a link

Is it possible to have a CMS that loads articles using ajax, where the article is loaded through a function with parameters, and when a certain link is clicked, it redirects to the target page and launches the function on that page? For instance, let' ...

Identify input elements that specifically contain an onclick event

Several of the input elements on my page have a function called setSomeFunction() that either shows or hides certain divs when clicked. I know I can locate all the input elements using document.getElementsByTagName("input") and store them in an array. How ...

Animating with React JS using JSON data sources

Currently, my project involves using React/Redux to store animation data in JSON and display it on a React page. The challenge lies in implementing the animations correctly while utilizing setTimeout for pauses and setInterval for movement. The Animation ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...