E
E
Egor2014-10-27 18:33:07
JavaScript
Egor, 2014-10-27 18:33:07

Angularjs. Why do page changes only happen after $apply?

There are 2 inputs

<input type="text" class="search-input real-search-input" data-ng-hide="showFakeInput"/>
<input type="text" class="search-input fake-search-input " disabled="disabled" data-ng-show="showFakeInput" />

The controller listens for events. The events themselves are called from the directive.
$scope.showFakeInput = false; 

$rootScope.$on('showFakeSearchInput', function () {
      $scope.showFakeInput = true;
});

$rootScope.$on('hideFakeSearchInput', function () {
     $scope.showFakeInput = false;            
});

The first time the 'showFakeSearchInput' event is called, everything works fine. The first input ('.real-search-input') disappears and .fake-search-input appears.
But if you then call 'hideFakeSearchInput', then no changes occur. That is, the variable changes, but .real-search-input remains hidden, while .fake-search-input remains visible.
If you do so
$rootScope.$on('hideFakeSearchInput', function () {
     $scope.showFakeInput = false;        
     $scope.$apply();    
});

That all works as it should.
Why is this happening and is it possible to do without $apply ?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Sergey, 2014-10-27
Protko @Fesor

You do not understand how data-binding works in Angular. That is, you did not understand the very cornerstone on which the angular is based.
$apply invokes a $digest loop on the rootScope that compares the current value with the last saved value. If there are changes, the watcher starts.
So the short answer is no, nothing will work without $apply. Long answer - www.sitepoint.com/understanding-angulars-apply-digest

A
Andrey Zenkov, 2014-10-27
@andreyzenkov

Read - habrahabr.ru/post/201832 , very well chewed.

E
Egor, 2014-10-27
@ByKraB

I'm reading this

ata binding means that when you change something in the view, the scope model automatically updates. Similarly, whenever the scope model changes, the view updates itself with the new value

For me, everything is done in the context, i.e. in the controller, the standard directives ng-show, ng-hide are used. Why should I call $apply if I only use standard Angular directives and don't change anything outside of Angular?

_
_ _, 2014-10-28
@AMar4enko

Show calling an event from a directive. I assume the problem is there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question