2013-05-06 72 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