当我使用ng-click时,可以通过id获得html的元素,但是使用ng-init时,我会得到null。请检查我的笔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);
};
}]);
最佳答案
您可以通过 Angular $ timeout来获取它,该方法要等到 Angular 循环结束并且元素已呈现 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))
});
};
}]);