如何使用$(target)inside指令?

时间:2016-02-02 22:27:51

标签: javascript jquery css angularjs

我用两个块构建了一个时间选择指令。问题是在指令模板内的某些块上捕获目标事件。 指令模板:

<div class='time-picker-container'>
    <div class='block1' ng-click='show()'>1</div>
    <div class='block2' ng-show='selectVisible'>2</div>
</div>

JS:

scope.selectVisible = false;
scope.show = function() {
    scope.selectVisible = scope.selectVisible ? false : true;
}
$rootScope.$on('documentClicked', function(inner, target) {
    //try to hide div.block2 if user make click outside block.
});

基本思路:当用户点击文档时,在div.block2之外,块消失。当用户点击div.block2块中的某些内容时,保持可见。

运行功能:

angular.element(document).on('click', function(e) {
        $rootScope.$broadcast('documentClicked', angular.element(e.target));
    });

1 个答案:

答案 0 :(得分:0)

In your template, add $event as an argument to the ng-click handler function.

<div class='time-picker-container'>
    <div class='block1' ng-click='show($event)'>1</div>
    <div class='block2' ng-show='selectVisible'>2</div>
</div>

Then in your ng-click handler use stopPropagation() to prevent the outsideClickHandler from getting called.

angular.module("myApp").controller("myVm", function($scope, $document) {
    var vm = $scope;
    vm.selectVisible = false;

    vm.show = function(event) {
       console.log("inside click");
       event.stopPropagation();
       vm.selectVisible = vm.selectVisible ? false : true;
    }

    function outsideClickHandler(e) {
        console.log("outside click");
        $scope.$apply("selectVisible = false");
    }
    $document.on("click", outsideClickHandler);

    $scope.$on("destroy", function() {
        $document.off("click", outsideClickHandler)
    })
})

To prevent memory leaks, be sure to remove the $document click handler when the scope is destroyed.

The DEMO on JSFiddle.