Reputation: 1511
I have a paragraph element in html. The element is visible only if a value is true.I have used ng-if to check that. I am trying to access the element through getElementByID but it returns null.
However i am able to access the other paragraph element in the html where ng-if is not used. How do i access the paragraph element and get the value which is bound with angular directive?
Html
<!DOCTYPE html>
<html ng-app="testApp">
<head>
<script data-require="angular.js@*" data-semver="2.0.0-alpha.31" src="https://code.angularjs.org/1.4.0/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div class="pull-right" style="margin-top:50px;margin-right:100px" ng-controller="MainController">
<div>
<p id="link" ng-if="user.isAdmin">New Link</p>
<p id="test">
</div>
{{value}}
</div>
</body>
</html>
Angular JS
var app = angular.module('testApp',[]);
app.controller('MainController', ['$scope', function($scope) {
$scope.user={};
$scope.today = new Date();
$scope.user.isAdmin=true;
$scope.value = "Test123";
var objstatic = document.getElementById('link');
console.log(objstatic);//returns null
var objdynamic = document.getElementById('test');
console.log(objdynamic);
objdynamic.innerHTML="Dynamic Test";
}]);
Working copy is updated here Working Demo
Upvotes: 3
Views: 5298
Reputation: 11973
Try this
angular.element(document.getElementById('lnkmanage')).scope().$apply()
Upvotes: 0
Reputation: 7076
Use watch and check for change in the scope variable.
$scope.$watch('user.isAdmin', function(newValue, oldValue) {
if($scope.user.isAdmin) {
var objstatic = document.getElementById('lnkmanage');
console.log(objstatic);
}
});
Upvotes: 0
Reputation: 5267
The problem is that you're trying to access the element before the digest cycle has rendered it. If you change the code to use $timeout then you will see the element
$timeout(function() {
var objstatic = document.getElementById('lnkmanage');
console.log(objstatic);
}, 0);
Upvotes: 2