Flying Gambit Flying Gambit - 1 year ago 85
AngularJS Question

How to get a reference to an element in the template

I am trying to initialize a chart using angularJs (v1.5.8) but I am unable to initialize a new chart object like below as shown in the instructions

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, { ...

because I am unable to get a reference to the html element in the template. How to get it ?

angular.module("dashboard", ['ngAnimate', 'ngSanitize', 'ui.bootstrap'])
.component("exceptionChart", {
template: "<canvas class='{{$ctrl.class}}'></canvas>",
bindings: { class: '@' },
controller: function(){
// how do I get a reference to canvas

Answer Source

Inside your controller you can inject $element service to get access to template.

Ideally you should access that $element inside $postLink() lifecycle hook of component which will ensure that all the descendant directive has compiled.

controller: function($element){
    // how do I get a reference to canvas
    this.$postLink = function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download