jpi*_*ora 11 javascript coffeescript angularjs
我想看看我的隐藏,并在我的应用程序中的所有元素上显示表达式.
我知道我可以通过使用只返回参数的函数包装show指令来实现:
<div ng-show="catchShow(myShowExpr == 42)"></div>
Run Code Online (Sandbox Code Playgroud)
但是,我想在我的应用程序的所有输入中观看所有隐藏/显示,而上述内容还不够好.
我也可以重载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);
});
};
}];
Run Code Online (Sandbox Code Playgroud)
虽然那时我无法使用谷歌CDN ......
有没有人能想到这样做的更好的方式?
jpi*_*ora 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)
Run Code Online (Sandbox Code Playgroud)
转换为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));
Run Code Online (Sandbox Code Playgroud)