如何使angularjs指令知道它是否在页面上可见

时间:2014-05-01 16:22:18

标签: angularjs angularjs-directive

我有一些自定义指令,用于控制自定义验证。

这些指令可能被ngShow或ngHide指令隐藏在它自己的元素或祖先元素上。

如何让我的指示知道它是否隐藏? (这样当另一个控制器询问其内容时,它不会报告验证错误)

我想在指令的控制器上有一个方法可以检查指令的元素或其任何祖先元素是否具有ng-show / hide属性集,其中的表达式在其自己的作用域内进行计算以隐藏它......但这需要一定数量的逻辑和dom访问(慢),所以我希望有更好的方法。

2 个答案:

答案 0 :(得分:2)

如果您的指令声明如下:

<mydir ng-show='showThisDir'></mydir>

然后它链接到范围变量,如:

$scope.showThisDir = true;

然后将数据添加到指令的范围,所以它应该是这样的:

.directive('mydir', function() {
    return {
      restrict: 'E',
      scope: {
        someData: '=info',
        isShown: '='
      },
      template: 'some html'
    };

});

并将其添加到您的声明中,如下所示:

<mydir ng-show='showThisDir' is-shown='showThisDir'></mydir>

现在你的指令知道它是否显示

另一种方式可能是:

.directive('mydir', function() {
    function link(scope, element, attrs) {
        var display = element.css('display'); 
        // whether it is displayed, but this would get more complicated 
        // as you need to set watchers when you changed data and
        // recalculate the display value
    },
    return {
      restrict: 'E',
      scope: {
        someData: '=info',
      },
      template: 'some html'
    };

});

答案 1 :(得分:2)

我更喜欢这样一种方法,即指令不需要知道示波器上显示或隐藏其祖先的内容,并直接检查该元素以确定其是否可见。

if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;

如果元素因任何原因被隐藏,则上述脚本将返回false,对于元素本身,祖先或css或其他原因,它都是ng-show