I’m taking my first forays into Angular.js, which I’m extremely impressed by. One of Angular’s best features is its templating, with which you can specify separate html files (called “partials”) and load them in only when your application requires.

I ran into a stumbling block with partials, which is how to apply jQuery to a partial. I was having no trouble applying jQuery to anything in index.html, but it did not seem to work for my partials.

I realized I would have to try applying the jQuery only after the external HTML has been loaded in. The default widget we have in index.html (which the partial will be loaded into) is:


Unfortunately, ng:view does not have an onload attribute, but its cousin ng:include does. Replace


with


as you can see, when the partial finishes loading in, the “addjQuerytoPartial()” method will run. But where do you define this method?

The ng:include widget does not have access to global context (Thanks Vojta Jina), but only to the scope defined in the controller of its parent. I’ve been working with the tutorial files, so that parent is the body tag, and the controller is “PhoneCatCtrl”.

So open up controllers.js and in the function body of PhoneCatCtrl($route) add:

 this.addjQueryToPartial = function()
  {
    angular.element('a').click(function() //angular way of accessing jQuery
    {
      alert('yo');
    });
  }

And there you have it! Would like to further modularize adding jQuery to partials, at the moment whatever is defined on addjQuerytoPartial() runs on every single partial that’s loaded in, but we will have to leave that for another post :)



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam Protection by WP-SpamFree

Get Adobe Flash playerPlugin by wpburn.com wordpress themes