如何在页面上的任何位置单击时调用AngularJS指令的函数?

时间:2016-05-26 08:33:12

标签: javascript jquery angularjs angularjs-directive

我想在页面的任何位置单击调用close()函数,但不起作用。我写得像:

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

请帮助解决这个问题。

被修改

<div live-search my-data="data" ng-model="typeId" ></div>

2 个答案:

答案 0 :(得分:1)

尝试使用此clickElsewhere指令检测该DOM对象外的任何位置。

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

您可以在模板中使用它:

<div live-search my-data="data" ng-model="typeId" click-else-where="close()"></div>

答案 1 :(得分:0)

您可以在link

中编写link:function($scope, element, attrs)){ $scope.close = function(){ // Rest of the code } $('body').on('click',function(event){ $scope.close(); }) } 处理程序
pp <- pp + scale_color_manual(values = c("ECMWF"="red","NCEP"="blue","ECMWF+NCEP"="green","5"="red1","10"="orange","15"="yello3","20"="green3","15"="black"),limits = c("ECMWF","NCEP","ECMWF+NCEP","5","10","15","20"))
print(pp)