简体   繁体   English

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

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

Using Angular, I am creating a countdown timer app. 使用Angular,我正在创建一个倒数计时器应用程序。 When the timer reaches a certain point, the timer stops, a notification sound is played and a div with a button is created. 当计时器到达某个点时,计时器停止,播放通知音并创建带有buttondiv

Like so... 像这样

HTML: HTML:

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

Javascript: Javascript:

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

resetTimer() function inside of Angular timerControl controller Angular timerControl控制器内部的resetTimer()函数

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

It creates the button fine enough, but when I click it to call the resetTimer() function inside of the timerControl Angular controller, it isn't even entering the function, otherwise the console.log(111) would be showing 111 in my Google Dev Tools in Google Chrome. 它创建的按钮足够精细,但是当我单击它以在timerControl Angular控制器内部调用resetTimer()函数时,它甚至没有输入该函数,否则console.log(111)在我的Google中显示111 Chrome浏览器中的开发工具。 Seems like it could be an issue with the DOM or something like that. 似乎是DOM或类似问题。 I tried using jQuery and it seems like there isn't much information about this out there. 我尝试使用jQuery ,似乎那里没有太多信息。 Anyone encounter this before? 有人遇到过吗?

Angular doesn't know that you did the .innerHTML assignment. Angular不知道您执行了.innerHTML分配。 You have to tell it, by invoking $compile . 您必须通过调用$compile来告诉它。 See the docs: https://docs.angularjs.org/api/ng/service/$compile 请参阅文档: https : //docs.angularjs.org/api/ng/service/$compile

There's a quick tutorial about the process here: http://onehungrymind.com/angularjs-dynamic-templates/ 这里有关于该过程的快速教程: http : //onehungrymind.com/angularjs-dynamic-templates/

You should be able to do this just with Angular (without jQuery) and the variables you have set up in the view's controller. 您应该只使用Angular(无需jQuery)以及在视图控制器中设置的变量就能做到这一点。

You could handle the creation of the button using an ng-if directive and manage this condition for button creation through controller variables (scope of controller being vm below). 您可以使用ng-if指令处理按钮的创建,并通过控制器变量(下面的控制器范围为vm)管理此按钮创建条件。 Then call the resetTimer() function within the view's controller. 然后在视图的控制器内调用resetTimer()函数。

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM