Integrating Third-Party JavaScript Widgets with Angular

I was working on integrating a gauge widget into an Angular directive. The widget requires to be setup in JavaScript that looks something as follows:

var gauge = new JustGage({ id : "the-element-id", min: 0, max: 100, title: "Gauge Title" });

It makes sense to represent the gauge widget as its own directive, so I created a directive for that purpose. Then, this imperative/procedural code that manipulates the DOM should go in the ‘link‘ function of the directive. So far so good.

The gauge requires an element to render itself. The ‘id’ attribute of the gauge configuration specifies the ID of that element, which. In my case, I needed to specify the ID dynamically. The ID of the gauge element was supplied to the directive via an attribute:

<my-gauge id="{{model.id}}" ... ></my-gauge>


On first attempt to run, I got an error saying that the element was not found. After debugging a bit and Googling a lot, I found out that the problem is mentioned in this post:

     "Notice that when the link function runs, any attributes that contain {{}}'s are 
      not evaluated yet (so if you try to examine the attributes, you'll get undefined)."
Then came $observe to the rescue. $observe, as opposed to $watch, allows you to listen on changes in the attributes of the directive element via the ‘attrs’ object passed to the link function. So in my link function I did:
attrs.$observe('id', function(newValue) {
// initialize the gauge here
};
And that solved the problem.

Continue reading “Integrating Third-Party JavaScript Widgets with Angular”