Angular - Event for ng-hide and ng-show

14,872

Solution 1

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

Solution 2

Another way to approach is to $watch the attribute of ngShow - although this would need to be done within a directive (useful if you're show/hiding an already custom directive)

scope.$watch attrs.ngShow, (shown) ->
  if shown
    # Do something if we're displaying
  else
    # Do something else if we're hiding
Share:
14,872
jpillora
Author by

jpillora

I'm also on the GitHubs

Updated on June 13, 2022

Comments

  • jpillora
    jpillora almost 2 years

    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 ?