How to get html element by id passed from ng-init angular

I could get the html element by id when I use ng-click, but with ng-init I get null. please check my pen http://codepen.io/solidet/pen/pbJMjq

HTML

<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 mem ID: {{memId}} </span> <span ng-click="getMember(memId)"> click me <span> </div> 

Controller

 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); }; }]); 
+5
source share
3 answers

you can get it through angular $ timeout, which waits until angular completes the loop and displays the elements

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)) }); }; }]); 
+5
source

You cannot access the DOM elements in ng-init , as they are not yet added to the DOM at this point. Direct access to the DOM elements in angular is in any case disapproving, so perhaps rethink your code design.


See https://docs.angularjs.org/api/ng/directive/ngInit for an appropriate use of this directive.

There are only a few suitable uses of ngInit , for example, to smooth out the special properties of ngRepeat , as shown in the demo below; and for entering data through server scripts. Besides these few cases, you should use controllers instead of ngInit to initialize values ​​in the scope.

0
source

Here is another discussion that will more or less answer your question.

Getting an item inside ng-init and ng-repeat

-1
source

All Articles