Angular - ng-hide和ng-show的事件

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)

  • 我是OP ...在发布之前查看帐户. (18认同)
  • 在答案中低估了包括CoffeeScript在内?Owell.愤世嫉俗的人看什么都不顺眼. (11认同)
  • 由于认真的倾向,老兄回答了他自己的问题,这是一个完全有效的答案,语言圣战放在一边. (8认同)
  • "Coffeescript"标签添加了问题.向左倾斜回答.:) (2认同)