Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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>     
    <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);
  };
}]);
like image 234
chourn solidet Avatar asked Jun 06 '16 07:06

chourn solidet


1 Answers

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))
        });
    };

}]);
like image 191
Peter Wilson Avatar answered Oct 11 '22 16:10

Peter Wilson