Question

Can I do something like:

<div set-height-to="function(){$(this).css($(".sth-elem").height()}"></div>

!!!! I do not want to set height only but things more complicated like watching a CSS style of an element and set style of this element with some offsets, calculations or more.

I will have a link function inside directive and function out will be called at some places to make my directive much more flexible How can I bind an anonymous function not Controller function or some JavaScript code as an attribute in directive?

Was it helpful?

Solution 2

With Class.js, I can flexibly extend any directives.

(function (define) {
    "use strict";
    define([
        'BaseClass/BaseDirective',
        'BaseClass/Component'
    ], function (BaseDirective, Component) {
        var AnimateWhenHover = BaseDirective.extend({
            $animate: null,
            init: function ($animate, scope, element, attr) {
                this.$animate = $animate;
                this._super(scope, element, attr);
            },
            defineScope: function () {
                var data = this.$scope.$eval(this.$attr.animateWhenHover);

                this.$scope.selector = data.show;
                this.$scope.overAnimation = data.over || "l2r";
                this.$scope.outAnimation = data.out || "l2r";
            },
            defineListeners: function () {
                this.$element.hover(this.in.bind(this), this.out.bind(this));
            },
            in: function () {
                this.$element.css({"width": "auto"});
                this.$animate.addClass($(this.$scope.selector), this.$scope.overAnimation);
            },
            out: function () {
                this.$element.css({"width": "50px"});
                this.$animate.removeClass($(this.$scope.selector), this.$scope.outAnimation);
            }
        });

        return new Component("animateWhenHover", ["$animate", function ($animate) {
            return {
                scope: '@',
                restrict: 'A',
                link: function (scope, element, attr) {
                    new AnimateWhenHover($animate, scope, element, attr)
                }
            }
        }
        ]);
    });
}
(define));

OTHER TIPS

In your markup I would do this:

<div set-height-to=".sth-elem"></div>

And in your directive use this attribute to set the height of the element to the height of the selector that you have passed in.

In your directive's link function you can do something like this (syntax not verified)

element.css('height', $(attr.setHeightTo).height());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top