dynamically add a directive

5,531 views
Skip to first unread message

Efflam Daniel

unread,
Sep 28, 2012, 11:47:33 AM9/28/12
to ang...@googlegroups.com
Hi,
I would like to add a directive to an element only if some condition is true. 
For example add an iScroll directive only if the browser doesn't have overflow-scrolling:touch support.
Is there a preferred way to do that ?
Thx !

Pawel Kozlowski

unread,
Sep 28, 2012, 12:56:44 PM9/28/12
to ang...@googlegroups.com
Hi!

Maybe instead of adding a directive conditionally you should execute
its logic (compile and / or link) conditionally?

Cheers,
Pawel
> --
> You received this message because you are subscribed to the Google Groups
> "AngularJS" group.
> To post to this group, send email to ang...@googlegroups.com.
> To unsubscribe from this group, send email to
> angular+u...@googlegroups.com.
> Visit this group at http://groups.google.com/group/angular?hl=en.
>
>



--
Question? Send a fiddle
(http://jsfiddle.net/pkozlowski_opensource/Q2NpJ/) or a plunk
(http://plnkr.co/)
Need help with jsFiddle? Check this:
http://pkozlowskios.wordpress.com/2012/08/12/using-jsfiddle-with-angularjs/

Looking for UI widget library for AngularJS? Here you go:
http://angular-ui.github.com/

Efflam Daniel

unread,
Sep 28, 2012, 1:21:35 PM9/28/12
to ang...@googlegroups.com
Hi Pawel,
In fact, that is what I do for the moment :
app.directive('scroll', function() {
  return {
    restrict: 'EA',
    link: function postLink(scope, element, attrs) {

    var hasOverflowScrollingSupport = true; // for tests

    if(hasOverflowScrollingSupport){

    // use native scrolling with
    // -webkit-overflow-scrolling:touch;

      element.addClass('overflow-scrolling');

    }
    else {

    // use iScroll

    var opts = scope.$eval(attrs.scroll || attrs.scrollOpts || {}),
    scroll = new iScroll(element[0], opts);
   
    }
    }
  };
});

But I have already an iscroll directive. So maybe, the scroll directive could add the iscroll directive to the element if hasOverflowScrollingSupport is false. Is it possible to add a directive from a directive ?

Thx

Andy Joslin

unread,
Sep 28, 2012, 9:27:04 PM9/28/12
to ang...@googlegroups.com
Hi Efflam,

Inject the $compile service into your directive and use it.   http://docs.angularjs.org/api/ng.$compile

Efflam Daniel

unread,
Sep 30, 2012, 9:10:09 AM9/30/12
to ang...@googlegroups.com
Hi Andy,
For now the link function was enough for my needs. Seems like it's time to dive into the compile side ;)
Thank to both of you

digger69

unread,
Dec 20, 2012, 6:08:42 PM12/20/12
to ang...@googlegroups.com
Efflam, would love to see what you came up with.
Reply all
Reply to author
Forward
0 new messages