0

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?

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thanks!
Actually not. It doesn't work, it seems to call the function before canvas is loaded, so whent it gets to line "this.ctx = this.canvas.getContext("2d")" it says "cannot read property "getContext" from null. It only happens with ng-init, with ng-click it still works fine. So, seems like I need a way to trigger it when the html/canvas fully loads? Any idea?
0

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().

1 Comment

Thanks for the addition, I will make sure to look into it once I make everything work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.