简体   繁体   中英

How to call a function of AngularJS directive when click anywhere on page?

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>

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>

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();
      })
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM