当!元素被点击时,角度隐藏

时间:2016-02-11 03:25:19

标签: angularjs angularjs-directive angularjs-ng-repeat

我正在使用指令属性在ng-repeated tr中渲染一些td。对于每次迭代,有两个tr,第二个最初是隐藏的,直到用户点击第一个tr。单击另一个tr时,显示的tr被正确隐藏。但是,当我点击当前显示的tr之外的任何地方时,我需要隐藏显示的tr,而不仅仅是其他tr。这在我的指令中不起作用,因为每次触发click事件时,都会针对每个ng-repeat迭代计算documentClickHandler函数,即第一个eventOutsideTarget可以求值为true但其他值为false,因此closePreview()函数始终为调用。有什么想法吗?

<tr ng-repeat-start="campaign in vm.campaignData track by campaign.id" ng-click="vm.showCampaignPreview(campaign)" campaign-item campaign="campaign" campaign-options="vm.campaignOptions" close-preview="vm.hideCampaignPreview()">
</tr>
<tr ng-class-odd="'odd'" ng-class-even="'even'" ng-repeat-end ng-show="vm.selectedCampaign.id == campaign.id">
    <td colspan="8">{{ campaign.description }}</td>
</tr>

//指令

(function(){
'use strict';

angular.module('campaignApp')
.directive('campaignItem', ['$document', "$parse", function ($document, $parse) {
    return {
        restrict: 'A',
        scope: {
            campaign: '=',
            campaignOptions: '=',
            closePreview: '&'
        },
        controller: 'vsmsCampaignsController',
        templateUrl: 'campaign.tpl.html',
        link: function(scope, element, attr, controller) {
            var documentClickHandler = function (event) {
                var eventOutsideTarget = (element[0] !== event.target.parentElement) && (0 === element.find(event.target.parentElement).length);
                if (eventOutsideTarget) {
                    scope.$apply(function () {
                        scope.closePreview();
                        console.log('close preview');
                    });
                }
            };

            $document.on("click", documentClickHandler);
            scope.$on("$destroy", function () {
                $document.off("click", documentClickHandler);
            });
        }
    };
}]);

})();

// campaign.tpl.html

<td>{{ campaign.name }}</td>
<td>{{ campaign.priority }}</td>
<td>{{ campaign.status }}</td>
<td>{{ campaign.createdBy }}</td>
<td>{{ campaign.approvedBy }}</td>
<td>{{ campaign.releaseDate * 1000 | date:'short' }}</td>
<td>{{ campaign.expirationDate * 1000 | date:'short' }}</td>
<td>
    <select ng-init="selectedOption = campaignOptions[0]" name="campaignOption" class="form-control" ng-model="selectedOption" ng-options="option.name for option in campaignOptions track by option.value">
    </select>
</td>

0 个答案:

没有答案