使用 .innerHTML 创建 <button>。单击时,按钮不会调用 Angular 控制器中的函数

Created <button> using .innerHTML. When clicked, button isn't calling function in Angular controller

使用 Angular,我正在创建一个倒计时应用程序。当计时器到达某个点时,计时器停止,播放通知声音并创建 divbutton

像这样...

HTML:

<div id='test'></div> 

Javascript:

 document.getElementById('test').innerHTML= '<div id="break-div"><button id="4"ng-click="timerControl.resetTimer()">Back to work!</button></div>'

resetTimer() 函数在 Angular timerControl 控制器中

this.resetTimer = function(){
    console.log(111)
    _this.resetWorkFlow = true;
}

它创建的按钮足够好,但是当我单击它来调用 timerControl Angular 控制器内部的 resetTimer() 函数时,它甚至没有进入该函数,否则 console.log(111) 将在 Google Chrome 的 Google 开发工具中显示 111。似乎这可能是 DOM 或类似问题。我尝试使用 jQuery,但似乎没有太多关于此的信息。有人遇到过这个吗?

您应该能够仅使用 Angular(没有 jQuery)和您在视图控制器中设置的变量来执行此操作。

您可以使用 ng-if 指令处理按钮的创建,并通过控制器变量(控制器的范围是下面的 vm)管理按钮创建的条件。然后在视图的控制器中调用 resetTimer() 函数。

例如:

<div ng-if="vm.resetWorkFlow">
    <button id="4" ng-click="vm.resetTimer()">Back to work!</button>
</div>

Angular 不知道您完成了 .innerHTML 作业。您必须通过调用 $compile 来告诉它。请参阅文档:https://docs.angularjs.org/api/ng/service/$compile

这里有一个关于该过程的快速教程: http://onehungrymind.com/angularjs-dynamic-templates/