ysj dev
ysj dev

Reputation: 3

AngularJS call controller function in html

So, i'm doing some things mixing AngularJS and Canvas but I'm kind of noob in both.

In a controller, I have a function like this:

app.controller('headerController',function(){
 this.status = header; //This is declared down of this
 //Other properties of the controller

 this.init = function(){
 var thumbImg = document.createElement('img');
 thumbImg.src = this.status.drawUrl;
 this.canvas = document.getElementById(this.status.name);
 this.ctx = this.canvas.getContext("2d");
 this.ctx.save();
 document.getElementById('texto').textContent = 'sdaas'; //This is just to see fast if it has worked
 }
 });

And in html, I have this:

<div ng-controller="headerController as header">
    <canvas ng-attr-id="{{header.status.name}}" ng-click="header.init()" height="1000px" width="1000px"></canvas>
</div>

You see that with the ng-click I call the controller function, and that works fine. The problem is that I want to call the function without having to click it, but I don't understand angular that well to know how to do it. I've seen some things about $scope but that seems like something I'll have to study from scratch, and I can do everything I need right now just with this doubt solved (I don't have that much time to learn all about Angular right now..). It would be something like this:

    <div ng-controller="headerController as header">
        <canvas ng-attr-id="{{header.status.name}}" ng-click="header.init()" height="1000px" width="1000px"></canvas>
<script>
header.init();
</script>
    </div>

So, any idea to do it and keep it simple and clean?

Upvotes: 0

Views: 1208

Answers (2)

ext
ext

Reputation: 2903

In addition to the answer by @the_scion, if you are using angular 1.6 you should consider using a component which has $onInit that can be used instead of manually calling init().

Upvotes: 0

The scion
The scion

Reputation: 972

Use ng-init instead of ng-click and then it will intinal it without the click event.

<canvas ng-attr-id="{{header.status.name}}" ng-init="header.init()" height="1000px" width="1000px"></canvas>

Upvotes: 1

Related Questions