Home angularjs When using Scope. $ Apply ();

When using Scope. $ Apply ();

Author

Date

Category

Frequently, no wonder they write that this is a difficult topic for understanding. I did not understand how most.
Where to use this thing?

Example:

. Directive ('Clickable', Function () {
Return {
 RESTRICT: "E",
 Link: Function ($ Scope, Element, Attrs) {
  element.bind ('Click', Function () {
 $ scope. $ Apply (Function () {
   $ scope.user ++;
   $ scope.bar ++;
 });
  Console.log ('1')
  });
 }
}
});

without wrapping $ scope. $ Apply () Example will not work.

I do not know, I found such a note:

Important: Any browser events are called out of the visibility of Angularjs, so within your handlers such events you need to call $ scope. $ Apply


Answer 1, Authority 100%

So, what exactly is not clear? Functions $ Apply / $ Digest launch Dirty-Check, and if the data in $ scope has changed, then update the view, that’s all the magic. When you change the data inside Angular, for example, on the NG-Click, it calls the $ Apply method if your code is not performed via Angular, then you need to run Dirty-Check hands. Here are very approximate examples:

ng-click

& lt; button ng-click = "counter ++" & gt; counter & lt; / button & gt;

inside yourself angular, replaced this design to:

jqlite ('buck'). ON ('Click', Function (EVT) {
    EVT.PreventDefault ();
    $ scope.counter ++;
    $ scope. $ apply ();
});

or

$ timeout (function () {$ scope.foo = "bar";}, 100);
// Equivalent
SetTimeout (Function () {
  $ scope.foo = "Bar";
  $ scope. $ apply ();
}, 100);

All this is very about, but the point is that when you use binding or Angular methods, he causes $ Apply / $ Digest for you, that’s all, nothing complicated here.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions