Sunday, February 15, 2015

Adventures in Angular

I’ve been getting to know Angular.js a little bit. It’s very cool so far, but it also hurts my head just a bit. I’ll get there. I love the way it allows binding model data to presentation so you don’t have to do any extra coding to get them to reflect each other. I love the ease it gives to iterating over data to put it into the DOM. I’m not sure I’m entirely a fan of the quantity of tags it introduces into your HTML.

I successfully set up a navigation bar using partials. This lets you have a main html page with, say, a header and footer in place, and your navigation. But instead of having your navigation links go to other html files, you name your pages and link to them with a preceeding # sign, for example:


...

<nav>
  <ul>
    <li><a href="#/page1">Page 1</a></li>
    <li><a href="#/page2">Page 2</a></li>
  </ul>
</nav>
...
<div ng-view></div>
...
ng-view provides the magic: the "partial" html files will be loaded into this location in the page when the links are clicked. Then, in your Angular app.js file, include something like:

...

var thisApp = angular.module('thisApp', [
  'ngRoute'
]);

thisApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/page1', {
        templateUrl: 'partials/page-1.html',
        controller: 'aCtrl'
      }).
      when('/page2', {
        templateUrl: 'partials/page-2.html',
        controller: 'aCtrl'
      }).
      otherwise({
        redirectTo: '/'
      });
  }]);
The confusing square braces that encompass most of the .config() function are there to protect the code from minification. The process will replace variable names which can break Angular. So the variables names are first included in the list, and finally the function that takes them all as arguments. I’m not used to that yet. Anyway, once you get into the $routeProvider’s .when() function, you just include the link name that shows up after the # in the html, and an object including the URL of the partial that will fill in the ng-view section and the name of a controller (defined elsewhere)—the controller will set up any information that partial area needs.

So far so good: but then I tried to add a jQuery "dataTable" to my partial. Now, dataTables work by the table being all set up, and then calling ".dataTable()" on the jQuery object that returns it - but Angular does a lot of manipulating the DOM on its own, and doesn't provide an obvious "onPageLoad" to hook into. So if the table is being *built by Angular*, it's hard to call a function on it! So I ended up replacing it with a more Angular option, an ng-table.

No comments:

Post a Comment