chourn solidet chourn solidet - 6 months ago 254
AngularJS Question

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

I could get the element of html 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 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);
};
}]);

Answer

you could get it via angular $timeout which is wait until angular cycle finshed and elements 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))
        });
    };

}]);