1

I want to call close() function on click anywhere in page,but didn't work. I have written like:

var liveSearch = function () {
return {
    restrict: "A",
    scope: {
        myData: '=',
        ngModel: '='
    },
    templateUrl: "/js/app/common/template/livesearch.html",
    link: function ($scope, element, attrs) {

        var close = function() {
            $scope.status = "close";
        };

        $scope.open = function () {
            $scope.status = "open";
        };

        $(document).on('click',function(){
            close();
        });
    }
};
app.directive("liveSearch", liveSearch);

Please help to solve this problem.

Edited

<div live-search my-data="data" ng-model="typeId" ></div>
2
  • Can you share, how you are using this directive ?? Commented May 26, 2016 at 8:35
  • Please look at the edited section Commented May 26, 2016 at 8:39

2 Answers 2

1

Try using this clickElsewhere directive for detecting click anywhere outside that DOM object.

directive('clickElsewhere', function($parse, $rootScope) {
        return {
            restrict: 'A',
            compile: function($element, attr) {
                var fn;
                fn = $parse(attr['clickElsewhere']);
                return function(scope, element) {
                    var offEvent;
                    offEvent = $rootScope.$on('click', function(event, target) {
                        if (element.find($(target)).length || element.is($(target))) {
                            return;
                        }
                        return scope.$apply(function() {
                            return fn(scope);
                        });
                    });
                    return scope.$on('$destroy', offEvent);
                };
            }
        };
    });

You can use it like so in your template:

<div live-search my-data="data" ng-model="typeId" click-else-where="close()"></div>
Sign up to request clarification or add additional context in comments.

2 Comments

It work only textbox keydown event,not click event. This directive created for live search and when I try type for searching anything in textbox close() function call.
provided directive work on click - as it's stated in your question and in its code $rootScope.$on('click',...
0

You can write an click handler inside link

link:function($scope, element, attrs)){
    $scope.close = function(){
  // Rest of the code
   }       
    $('body').on('click',function(event){
      $scope.close();
      })
   }

Comments

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.