2013-05-06 70 views
11

我想观看我的应用程序中所有元素的隐藏和显示表达式。Angular - ng-hide和ng-show的事件

我知道我可以通过包装与刚刚返回的参数的函数演出指令做:

<div ng-show="catchShow(myShowExpr == 42)"></div> 

不过,我喜欢看全部隐藏/显示了跨在我的应用程序的所有输入和以上不够好。

我也可能超载ngShow/ngHide指令,虽然我需要重新评估表达式。

我也可以直接修改源,因为它很简单:

var ngShowDirective = ['$animator', function($animator) { 
    return function(scope, element, attr) { 
    var animate = $animator(scope, attr); 
    scope.$watch(attr.ngShow, function ngShowWatchAction(value) { 
     var fn = toBoolean(value) ? 'show' : 'hide'; 
     animate[fn](element); 
     //I could add this: 
     element.trigger(fn); 
    }); 
    }; 
}]; 

虽然那时我不能使用谷歌CDN ...

有没有一种更好的方式任何人能想到的做这个 ?

+1

可以编写自己的显示指令,而不是使用'ng-show' – charlietfl 2013-05-06 09:39:59

+0

我可以问问企业需要什么吗?我试图想,如果有更好的方法来做到这一点.. – 2013-05-06 13:39:14

+0

我有一个复杂的形式,当一个元素被隐藏,它需要被清除。目前,我在我自己的幻灯片[动画](http://code.angularjs.org/1.1.4/docs/api/angular.Module)中执行此操作。尽管如果我决定淡化一个元素,或者立即隐藏/显示,它很快就会变得非常黑。因此需要一个事件。 由于'ng-show'指令的实现非常简单,我可能只需要使用@ charlietfl的建议并实现我自己的指令。 – jpillora 2013-05-07 00:54:46

回答

22

下面是我想出(CoffeeScript中)

getDirective = (isHide) -> 
    ['$animator', ($animator) -> 
    (scope, element, attr) -> 
     animate = $animator(scope, attr) 
     last = null 
     scope.$watch attr.oaShow, (value) -> 
     value = not value if isHide 
     action = if value then "show" else "hide" 
     if action isnt last 
      scope.$emit 'elementVisibility', { element, action } 
      animate[action] element 
     last = action 
    ] 

App.directive 'oaShow', getDirective(false) 
App.directive 'oaHide', getDirective(true) 

到JavaScript的转换:

var getDirective = function(isHide) { 

    return ['$animator', function($animator) { 
    //linker function 
    return function(scope, element, attr) { 

     var animate, last; 
     animate = $animator(scope, attr); 
     last = null; 

     return scope.$watch(attr.oaShow, function(value) { 
     var action; 
     if (isHide) 
      value = !value; 

     action = value ? "show" : "hide"; 

     if (action !== last) { 
      scope.$emit('elementVisibility', { 
      element: element, 
      action: action 
      }); 
      animate[action](element); 
     } 

     return last = action; 
     }); 
    }; 
    }]; 
}; 

App.directive('oaShow', getDirective(false)); 
App.directive('oaHide', getDirective(true)); 
+18

我是OP ...在发布之前查看帐户。 – jpillora 2013-05-09 00:29:12

+2

“Coffeescript”标记已添加到问题中。 Downvote留在答案。 :) – 2013-05-09 14:58:32

+11

在答案中减少了包含CoffeeScript的投票数? Owell。愤世嫉俗的人看什么都不顺眼。 – jpillora 2013-06-02 06:38:43

0

另一种方式来处理是$watchngShow属性 - 尽管这将需要在指令内完成(如果您显示/隐藏已经定制的指令,则很有用)

scope.$watch attrs.ngShow, (shown) -> 
    if shown 
    # Do something if we're displaying 
    else 
    # Do something else if we're hiding