0

Using Angular, I am creating a countdown timer app. When the timer reaches a certain point, the timer stops, a notification sound is played and a div with a button is created.

Like so...

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() function inside of Angular timerControl controller

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. Seems like it could be an issue with the DOM or something like that. I tried using jQuery and it seems like there isn't much information about this out there. Anyone encounter this before?

2 Answers 2

2

Angular doesn't know that you did the .innerHTML assignment. You have to tell it, by invoking $compile. See the docs: https://docs.angularjs.org/api/ng/service/$compile

There's a quick tutorial about the process here: http://onehungrymind.com/angularjs-dynamic-templates/

Sign up to request clarification or add additional context in comments.

4 Comments

@tangentstrom Thanks for pointing me in the right direction. Where do you put your directives? In the corresponding controller of the template?
@tangentstrom Also, I've never made a directive before, nothing really seems to make sense. :/
Also, I don't really understand the docs. What does $compile do anyway?
The $compile service is where the JavaScript for the ng-click directive is stored. When you use the $compile service it instantiates the stored JavaScript and links it to the scope that you specify.
0

You should be able to do this just with Angular (without jQuery) and the variables you have set up in the view's controller.

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). Then call the resetTimer() function within the view's controller.

For example:

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

1 Comment

Thanks for your suggestion, but that didn't work. I think it has to do with the fact that the content I am displaying to the page is dynamic on the DOM (since I am using innerHTML()) and angular doesn't know that that button exists because of the corresponding disconnect...

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.