4

I have a angular controller which needs to reset whenever the user clicks outside the scope of the controller. How do I do this?

Sample html:

<div id='parent'>
    <div id='1' ng-controller="ctrl1">
        <!--other things-->
    </div>

    <div id='2' ng-controller="ctrl2">
        <!--other things-->
    </div>
</div>
<div id="parent2">
        <!--other things-->
</div>

I want to be able to reset ctrl2 if a click occurs outside of ctr2 when the click occurs outside of div2

ctr2 has a reset function defined inside

Ranjith Ramachandra
  • 10,399
  • 14
  • 59
  • 96

2 Answers2

4

If you are wanting a reset when the click happens within a sibling div, then the fact that the controllers share $scope should make that fairly straightforward. If you want to reset the div when a click happens anywhere else on the page, then you should set the "resetting" div as a directive, binding the $window object to a click handler:

app.directive('reset', function($window){
  return {
    template: '<div ng-class="{red: directiveToggler}">I\'m in 2' +
              ' - click me to turn red, click anywhere else to turn me normal'+
              '</div>',
  controller: function($scope){
    $scope.directiveToggler = true;
  },
  link: function(scope, element){

    var w = angular.element($window);
    w.bind('click', function(e){

      if (e.target != element[0].children[0]){
        scope.directiveToggler = false;
        scope.$apply();

      } else {
        scope.directiveToggler = true;
        scope.$apply()
      }
    })
  }
  }
})

Note that there are probably waaay better ways of handling the class/style changes than what I have set up, but the question was about click events ;).

Here's a plunk to demo

rGil
  • 3,719
  • 1
  • 22
  • 30
1

You can use the $rootScope to broadcast events to other controllers. See this JSFiddle: http://jsfiddle.net/simpulton/XqDxG/

Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45