AngularJS在html中调用控制器函数

时间:2017-11-18 17:26:06

标签: javascript angularjs

所以,我正在做一些混合AngularJS和Canvas的事情,但我在两者中都是一种菜鸟。

在控制器中,我有这样的功能:

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

在html中,我有这个:

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

你看到用ng-click我调用控制器功能,这很好用。问题是我想调用该函数而不必点击它,但我不太了解角度,知道如何去做。我已经看过一些关于美元范围的事情,但这似乎是我必须从头开始学习的东西,我现在可以做所有我需要的东西,只是这个疑问已经解决了(我没有那个现在花很多时间学习Angular ...)。它会是这样的:

    <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>

那么,有什么想法,并保持简单和干净?

2 个答案:

答案 0 :(得分:1)

使用ng-init而不是ng-click,然后它将在没有click事件的情况下使用它。

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

答案 1 :(得分:0)

除了@the_scion的回答之外,如果您使用的是角度1.6,则应考虑使用component $onInitinit()可以使用using LinqKit;而不是手动调用// change terminaionDate to Expression<Func<MyEntity, DateTime>> static Expression<Func<MyEntity, bool>> GetFilterPredicate(Expression<Func<MyEntity, DateTime>> terminationDate) { // note Invoke Expression<Func<Error, bool>> filter = c => terminationDate.Invoke(c) <= DateTime.Now; // note Expand return filter.Expand(); } 。< / p>