我想在页面的任何地方单击时调用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>
最佳答案
尝试使用此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>