M
M
Max2016-04-05 22:36:12
JavaScript
Max, 2016-04-05 22:36:12

How to draw the value of a timer implemented through a service without juggling the entire scope?

Hello. There is a desire to display several countdown counters on the old page using angular. To do this, I wrote a service: https://jsfiddle.net/j2wz86m2/ which will do all the calculations and give the desired result for each counter. At first glance, everything works well, but I noticed a very serious problem that could potentially lead to a large amount of memory being consumed. So, what I do:
1. Inject a dependency on the given service $counterService into
the controller 2. I start each counter:

$counterService.getInstance('counter' + id).startCounter(data.end);

3. In the controller, I create a method to get the value of the counter by its name:
$scope.getCounter = function(counterName) {
    $counterService.getInstance(counterName).counterValue();
}

But in this case, the following problem arises:
Since $timer starts a digest after the callback is executed, the data of all counters are correctly drawn in the DOM, but in addition to calling the getCounter() method , all scope methods are also called, which does not suit me very much. After all, I do not need to call all the methods, I only need to call 1 to get the new counter value. And since all methods of the scope are called, this leads to increased memory consumption. I know that $timer takes a third parameter that can disable the start of the digest, but in this case, the timers are ticking, but the page is not updated.
Is there any way to correctly render timer values ​​without calling unnecessary scope methods?
PS. You can see a working example here: https://jsfiddle.net/j2wz86m2/6/ (something that should not fall into the console when updating the counters)
UPD. I suspect that the solution I'm interested in is knocked out of the concept of angular. @jackkum 's idea made me think that it is possible to get the value in the directive and render the value using jQuery html() or text() , which of course is out of the angular concept, and 2 timeouts is not the best solution, but it works nonetheless properly. As a result, the final version turned out like this:
https://jsfiddle.net/j2wz86m2/7/
If you have better ideas, I'd love to take a look
Special thanks to @jackkum for the tip

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kumanin, 2016-04-06
@matios

You can make each counter in different controllers, but this is not very convenient.
You can make a plnkr.co directive

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question