Cautionary Tale for Angular Developers


Okay, now take a moment to watch this video

I’m sure after watching it, you may have realized that I’m not here to talk about why Neo falls into coma by stopping sentinels. Instead I’m going to talk about why my application got crashed the same way in Windows 8 RT webview and what I learned.

The Reality

An Application was built on top of Angular.js and Twitter Bootstrap for Desktop, Android, iOS, and Windows8. For touch devices, we’d created a Native wrapper around which loads the application in a webview. It looked fine in Android and iOS devices but was crashing in Windows8 RT upon opening a Bootstrap Modal popup. And I had no clue why Windows8 RT alone?

This is what I was using to open a modal window. I know its very bad to do the imperative DOM manipulation inside controller but as there were no directives bound to .modal I believed its safe to use it.

$('.modal').modal({backdrop: 'static'});

But I was wrong. In Windows8 RT, the above line was throwing an error “Object [object Object] has no method ‘modal'”. My guess is that I must be executing bootstrap code in middle of $digest cycle or something.

The Fix

To fix this issue I could either move that code in a custom directive and toggle modal’s state or use Angular UI Bootstrap. I decided to go with the latter. Finally I learned a very hard lesson while fixing the issue that one should spend some time to get it right than just get it done.

Follow the best practices or get ready to be bitten.

So I’ve used AngularUI Bootstrap modal directive to instead of doing DOM manipulation in the controller.

var App = angular.module('App', ['ui.bootstrap']);
App.run(function($rootScope) {
    $rootScope.opts = {
        backdrop: true,
        backdropClick: false,
    };
    
    $rootScope.modalOpen = false;
});

Finally updated the DOM as follows:

  <button class="btn btn-primary btn-large" ng-click="modalOpen = true">Open Modal</button>

  <div class="modal hide" options="opts" modal="modalOpen">
    <div class="modal-header">
      <h3>Modal Header</h3>
    </div>
    <div class="modal-body">
      Modal Body goes here...
    </div>
    <div class="modal-footer">
      <div class="btn" ng-click="modalOpen = false">Close</div>
    </div>
  </div>
Advertisements

4 thoughts on “Cautionary Tale for Angular Developers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s