Search code examples
javascriptangularjsslimscroll

Angular dynamically adding directive


I want to dynamically use angular-slimscroll in my webpage. The directive looks something like this:

<div id="scroll" slimscroll="{slimscrollOption: value}">
    Scroll Content
</div>

How can I dynamically add slimscroll="{slimscrollOption: value}" into #scroll div and have it functioning with angular-slimscroll?


Solution

  • You can create a directive, some thing like that:

    JS

    angular.module('myApp',[])
    .controller('MyCtrl', function ($scope) {})
    .directive('myScroll', ['$compile', function($compile) {
        return {
            scope: true,
            link: function(scope, element, attrs) {
    
                element.attr('slimscroll', '{slimscrollOption: value}'); 
                element.removeAttr('my-scroll'); 
                $compile(element)(scope);
    
            }
        };
    }]);
    

    HTML

    <div id="scroll" my-scroll>
        Scroll Content
    </div>
    

    The key is you need to $compile the element again to dynamically add angular-slimscroll. And removing attribute 'my-scroll' to advoid infinity loop while compiling.

    You can see my answer here also (it is the same as your case, I think): How to add toggling of the disabled state of an input via double click from inside a directive?