質問

I have the following directive:

app.directive('showonhoverparent',
  function() {

    return {
      link : function(scope, element, attrs) {
        element.parent().bind('mouseenter', function() {
          console.log(attrs.showonhoverparent);
          element.fadeIn(attrs.showonhoverparent);
        });
        element.parent().bind('mouseleave', function() {
          element.fadeOut(attrs.showonhoverparent);
        });
      }
    };
  }
);

And I use it like this in the html:

<div class="img-text" showonhoverparent="2000">{{image.title}}</div>

or:

<div class="img-text" showonhoverparent="'slow'">{{image.title}}</div>

For some reason, no matter what I pass as the as the attribute value, the fadein/out speed id always the default speed, as if no parameter is passed to it! any ideas why?

役に立ちましたか?

解決

fadeIn/fadeOut checks the actual type of the parameter.

In the first case, "2000" is a string, so it thinks you're passing in something like "fast" or "slow" and doesn't treat it as milliseconds.

In the second case, you don't need the single quotes in showonhoverparent="'slow'". The quotes are included in the string and it's not able to match the speed keywords.

Add a check for numeric in the directive and it should work...

app.directive('showonhoverparent',
  function() {

    return {
      link : function(scope, element, attrs) {
        element.parent().bind('mouseenter', function() {
          console.log(attrs.showonhoverparent);
          element.fadeIn(getDuration(attrs.showonhoverparent));
        });
        element.parent().bind('mouseleave', function() {
          element.fadeOut(getDuration(attrs.showonhoverparent));
        });

        function getDuration (duration) {
          return (parseInt(duration, 10) > 0) ? parseInt(duration, 10) : duration;
        }
      }
    };
  }
);

Jsbin: http://jsbin.com/rofosibu/1/

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top