Cosmin Oprea Cosmin Oprea - 1 month ago 14
AngularJS Question

Access element from ng-include html

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.

Answer

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')
}
Comments