如何获得对模板中元素的引用 [英] How to get a reference to an element in the template

查看:31
本文介绍了如何获得对模板中元素的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用angularJs(v1.5.8)初始化图表,但无法像

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, { ... 

因为我无法获得模板中html元素的引用.如何获得?

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
    }
});

推荐答案

在您的控制器内部,您可以注入 $ element 服务以访问 template .

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

理想情况下,您应该在组件的 $ postLink()生命周期挂钩内访问该 $ element ,这将确保所有后代指令均已编译.

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() {
       console.log($element)
    }
}

这篇关于如何获得对模板中元素的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆