[英]Angular - Event for ng-hide and ng-show
我想看看我的隱藏,並在我的應用程序中的所有元素上顯示表達式。
我知道我可以通過使用只返回參數的函數包裝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 ......
有沒有人能想到這樣做的更好的方式?
這就是我的想法(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));
另一種方法是$watch
ngShow
的屬性 - 雖然這需要在一個指令中完成(如果您顯示/隱藏已經自定義的指令,則很有用)
scope.$watch attrs.ngShow, (shown) ->
if shown
# Do something if we're displaying
else
# Do something else if we're hiding
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.