derlin
5/10/2016 - 11:40 AM

Angular directives and utils

Angular directives and utils

  // from http://stackoverflow.com/questions/14544741/how-can-i-make-an-angularjs-directive-to-stoppropagation
  .directive('stopEvent', function () {
        return {
            restrict: 'A',
            link: function (scope, element, attr) {
                if(attr && attr.stopEvent)
                    element.bind(attr.stopEvent, function (e) {
                        e.stopPropagation();
                    });
            }
        };
     });
(function () {
    angular.module('derlin.link', [])
        .directive('activeLink', linkDirective);

    function linkDirective($location, $rootScope) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var clazz = attrs.activeLink;
                var path = attrs.href;
                path = path.substring(1); // hack because path does not return including hashbang
                scope.location = $location;
                scope.$watch('location.path()', function (newPath) {
                    $rootScope.path = newPath.substring(1); // remove start slash
                    if (path === newPath) {
                        element.addClass(clazz);
                    } else {
                        element.removeClass(clazz);
                    }
                });
            }
        };
    }

})();
(function () {
    angular.module('derlin.hover', [])
        .directive('hoverClass', hoverClass);


    // how to use: 
    // <ANY hover-class="default-class:hover-class">...
    // any of the two can be empty, but the ":" MUST be present.
    function hoverClass() {
        return {
            restrict: 'A',
            scope: {
                hoverClass: '@'
            },
            link: function (scope, element) {
                var split = scope.hoverClass.split(":");

                var clsOut = split[0];
                var clsIn = split[1];

                element.addClass(clsOut);

                element.on('mouseenter', function () {
                    element.removeClass(clsOut);
                    element.addClass(clsIn);
                });
                element.on('mouseleave', function () {
                    element.removeClass(clsIn);
                    element.addClass(clsOut);
                });
            }
        };
    };

})();
// some useful directives and snippets for angularJS 1.X applications