Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Event for ng-hide and ng-show

I'd like to watch my hide and show expressions on all elements in my app.

I know I can do it by wrapping the show directive with a function which just returns the argument:

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

However, I'd like to watch all hide/shows across all inputs in my app and the above isn't good enough.

I could also overload the ngShow / ngHide directives though I'd need to reevaluate the expression.

I could also just modify the source since it's quite simple:

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);
    });
  };
}];

Though then I couldn't use the Google CDN...

Is there a nicer way anyone can think of to do this ?

like image 730
jpillora Avatar asked May 06 '13 06:05

jpillora


1 Answers

Here's what I've come up with (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)

Converted to 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));
like image 189
jpillora Avatar answered Sep 23 '22 15:09

jpillora