Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize Zurb Foundation 5 in an AngularJS Directive

I've created three plunkrs to illustrate my problem. I'm trying to create an AngularJS Directive that will initialize foundation and apply the necessary javascript to the loaded template. At first I was trying to use ngInclude to add the Foundation 5 nav bar to all of the pages of my website. The top bar works as expected when the html is directly applied to a partial. When the html is added in a directive, such as ngInclude, the top bar looses all its functionality. I suspect that this was because foundation is not getting initialized after the template is added by the directive. As a solution I created a custom directive that would initialize foundation and compile the html template. Initializing foundation the way I do freezes the application. Anyone have a solution to this?

Trying to achieve this without resorting to Angular UI.

Example 1: HTML directly applied to the view. Works as expected, when you click on the menu dropdown the pages are displayed.

http://plnkr.co/edit/aQc6j2W9MpRuJo822gAF?p=preview

Example 2: ngInclude used to load template to dom. No functionality is achieved, when you click on the menu dropdown nothing happens.

http://plnkr.co/edit/fSS3FfYKFilMXsIkYUHg?p=preview

Example 3: Created separate directive to replace ngInclude that would initialize foundation, compile, and load the template to DOM. Can't provide a plunkr because it would just freeze up, but here is the code.

.directive('testdirective', function($compile) {
    return {
    restrict: 'AE',
        templateUrl: 'partials/includes/nav.html',
        link: function(scope, element, attrs) {
                $compile($(document).foundation())(scope);
        }
    }
})

applied in partial by:

<div testdirective></div>
like image 771
rjm226 Avatar asked Jan 14 '14 18:01

rjm226


1 Answers

Do this:

link: function(scope, element, attrs) {
  $compile(element.contents())(scope);
  $(document).foundation();
}

If you compile the element itself, you create an infinite loop:

$compile(element)(scope); //fail

Always be sure that you only compile the element's contents:

$compile(element.contents())(scope); //win

It seems that you are compiling the whole document and creating the infinite loop.

You can probably just do this:

templateUrl: 'partials/includes/nav.html',
compile: function() {
  $(document).foundation();
}

because the template will be automatically compiled so you don't have to do it manually.

Note: it's best practice to inject and use Angular's $document, which is a wrapper for document that helps in testing. $($document).foundation();

like image 166
m59 Avatar answered Nov 07 '22 12:11

m59