Reputation: 595
I have an html that is included in several htmls that are controlled by several different controllers . I want to access elements from that included html by id in every controller . I will post below my html that is included in every html:
<ul class="nav menu" >
<li id="tom_nav_bar"><a href="/#tom">
<svg class="glyph stroked dashboard-dial">
<use xlink:href="#stroked-dashboard-dial"></use>
</svg>
BEX Dashboard</a></li>
<li id="sonar_nav_bar"><a href="#/sonar">
<svg class="glyph stroked chevron right">
<use xlink:href="#stroked-chevron-right"/>
</svg>
Sonar</a></li>
<li id="teamcity_nav_bar"><a href="/#teamcity">
<svg class="glyph stroked chevron right">
<use xlink:href="#stroked-chevron-right"/>
</svg>
TeamCity</a></li>
<li id="kpi_definitions_nav_bar"><a href="#/kpi_definitions">
<svg class="glyph stroked chevron right">
<use xlink:href="#stroked-chevron-right"/>
</svg>
Kpi Definitions</a></li>
<li id="credit_risk_custom_report_nav_bar"><a href="#/department_custom_report">
<svg class="glyph stroked chevron right">
<use xlink:href="#stroked-chevron-right"/>
</svg>
CREDITRISK Custom Report (beta)</a></li>
</ul>
Let's name the code html : navbar.html. Now I will post one from 4 htmls where I included the above code:
<div ng-include src="'navbar.html'" class="col-sm-3 col-lg-2 sidebar"></div>
And now in my controllers I want to access for example 'tom_nav_bar' id , but I'm not able to do it:
document.getElementById("tom_nav_bar").className = "active";
Here getElementById is returning null.
Upvotes: 1
Views: 1074
Reputation: 319
First, your syntax might be wrong https://docs.angularjs.org/api/ng/directive/ngInclude
Also, maybe because your partial hasnt loaded yet at the moment of calling
document.getElementById
try putting this in your scripts:
function GetElement(idselector) {
document.getElementById(idselector).className = "active";
}
and then when you include your navbar, use this function in the onload parameter of ng-include:
<div
ng-include="navbar.html"
[onload=GetElement("tom_nav_bar")]
class="col-sm-3 col-lg-2 sidebar">
</div>
Upvotes: 1
Reputation: 105499
You shouldn't access DOM from the controllers. This is almost impossible to test, hard to refactor and adds confusion because DOM manipulation is mixed with presentation logic
I suggest you create a simple directive 'insert-navbar' with the following template:
<div ng-include src="'navbar.html'" class="col-sm-3 col-lg-2 sidebar"></div>
and use it like this in every place it needs to be used:
<insert-navbar>
Then, inside the link
function of that directive you should be able to access the element like this:
link: function(scope, element) {
element[0].querySelector('#tom_nav_bar')
}
Upvotes: 2