0

I have a variable-isTelephoneMenuOpen that makes my menu Open. Now on click on anywhere else in window I want to make it disappear. I tried this code but Its not working.Please help

  $document.on('click', function (event) {
      if (this.isTelephoneMenuOpen = true) {
           console.log("close menu");
           this.isTelephoneMenuOpen = false;
           // return $document.off('click', event);
      }
});

6
  • Please note that everything is in the same controller Commented Jan 10, 2017 at 9:43
  • This is not how we use AngularJS. Check ng-show, ng-if and ng-click Commented Jan 10, 2017 at 9:44
  • Also notice that your condition is ASSIGNING the value, not comparing it. It will ALWAYS evaluate to true Commented Jan 10, 2017 at 9:49
  • @casraf:Thanks . $document.on('click', function (event) { if (self.isTelephoneMenuOpen == true) { console.log("close menu"); self.isTelephoneMenuOpen = false; console.log("self val --->"+ self.isTelephoneMenuOpen); console.log("this val --->"+ this.isTelephoneMenuOpen); //return $document.off('click', event); } }); I corrected the code.Its working ...But when I hover to the Menu item list disappears. Commented Jan 10, 2017 at 10:04
  • @Weedoze:Thanks for suggestion.But how to make that variable false when a user click anywhere else in the window and without using directive ? Commented Jan 10, 2017 at 10:21

1 Answer 1

1

The this keyword inside event handlers binds to the element emitting the event, not the this context of the parent function. Explicitly bind the parent this context to a variable.

  var $ctrl = this;

  $document.on('click', menuClickHandler);

  this.$onDestroy = function() {
      $document.off('click', menuClickHandler);
  };

  function menuClickHandler(event) {
      if ($ctrl.isTelephoneMenuOpen) {
           console.log("close menu");
           $ctrl.isTelephoneMenuOpen = false;
           $rootScope.$apply();
      }
  }

Click events come from outside the AngularJS framework. Use $apply to initiate an AngularJS digest cycle to update the DOM.

-- AngularJS Developer Guide (v1.1) - Concepts - Runtime.

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

3 Comments

Very nice explanation, one remark though: digesting the scope in which the binding is to be re-evaluated is much better (faster) then forcing a complete digest on all elements using $rootScope.$apply().
I think you are confusing $digest with $apply. $apply executes an expression function and then initiates a root.$digest. It really doesn't matter from which scope it is started.
My point is that it is always better to call $digest in the current scope instead of calling it in root, which $apply does.

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.