ui-bootstrap Oddity

The <tab> element from the Angular-UI project’s ui-bootstrap has an oddity with the activate attribute, it seems, when calling a function to determine whether a tab should be active. For example,


<tab ng-repeat="u in foo.units" active="activeTab(u)">

causes JavaScript errors and the tabs do not function correctly. Poking around in the internals of ui-bootstrap-tpls.js lead to me discover that in this case the code

if (attrs.active) {
    getActive = $parse(attrs.active);
    setActive = getActive.assign;

leaves setActive to undefined. The JavaScript later attempts to call setActive, which crashes and burns of course.

I was able to work around the problem by copying the essentials of the activeTab function into the active attribute, e.g.


<tab ng-repeat="u in foo.units" active="bar.isPlugh == u.state.isPlugh">

Posted in Programming | Tagged , , , , | Leave a comment

Quick Jasmine 2 Reference

The Jasmine 2 Introduction is a wonderful combination of a demo and reference. However I’d rather not have to scroll through to find something.

Matchers

Jasmine Description Example
not Negation expect(‘foo’).not.toBe(‘bar’)
toBe() === expect(’1′).not.toBe(1)
toEqual() Smarter check; should handle simple objects. expect(’1′).toEqual(1)
toMatch() Regex expect(’1′).toMatch(/\d/)
toBeDefined() !== undefined expect(1).toBeDefined()
toBeUndefined() === undefined expect().toBeUndefined()
toBeNull() === null expect(null).toBeNull()
toBeTruthy() true expect(’1′).toBeTruthy()
toBeFalsy() false expect(”).toBeFalsy()
toContain() in array expect([1,2]).toContain(2)
toBeLessThan() < expect(1).toBeLessThan(2)
toBeGreaterThan() > expect(1).toBeGreaterThan(0)
toBeCloseTo() floating point comparison expect(2.0/2.0).toBeCloseTo(1)
toThrow() pass in function reference expect(func).toThrow()

Notes on toThrow()

toThrow() takes a function reference, which it calls with no parameters. If you need to pass parameters, you can wrap it in another function(){}.

If called with no parameters, it passes on any exception. If called with a parameter, the exception must equal the parameter.

Posted in Programming | Tagged , , , , , , , | Leave a comment

Regular Expression for Validating Floating-Point Numbers

This is more of a classroom assignment problem, but it creeps up from time to time in the real world. The best I’ve been able to come up with over the years is:


/^\s*[-+]?(\d*\.?\d+|\d+\.)(e[-+]?[0-9]+)?\s*$/i;

Why?

I was asked why bother with this when JavaScript has a parseFloat() function.

This can be useful when one must ensure that a string contains an actual floating-point number and nothing else.

The JavaScript parseFloat() function will accept any string (including garbage like alphabetic characters) so long as the first sequence of characters is a float.

The MDN page gives the following examples, all of which return 3.14:

parseFloat("3.14");
parseFloat("314e-2");
parseFloat("0.0314E+2");
parseFloat("3.14more non-digit characters");

The last example contains a string that is clearly not a valid number.

Posted in Programming | Tagged , , , , , , | Leave a comment

Set Background Colour with AngularJS

From the “I can’t believe I had to look it up” department:

One can use ngStyle to programmatically set the background colour of an element. This is arbitrary ugly code that demonstrates the concept:

<span ng-style="{background: item.color}">
Posted in Uncategorized | Leave a comment

AngularJS Directives: Expression or Interpolation?

AngularJS seems to be inconsistent on whether a directive can contain an expression or requires an expression to be wrapped in interpolation brackets {{ thusly }}.

Here is a partial list of directives consisting of ones that have bitten me.

Directive Expression or Interpolation? Notes
ng-class Expression Accepts an object, array or string.
ng-src Interpolation
ng-href Interpolation
ng-srcset Interpolation
ng-style Expression Give it an object.
ng-include Interpolation Accepts a string.
Posted in Programming | Tagged , , , | Leave a comment

Django and AngularJS POST

I’m converting some code that uses jQuery to post data to Django over to AngularJS. The POSTed data wasn’t coming across as expected.

By default AngularJS and jQuery use two different methods of packaging data. According what I’ve gleaned from googling:

  • jQuery posts using a content type of application/x-www-form-urlencoded and serializes the data using the foo=bar&fuz=baz method.
  • AngularJS posts using a content type of application/json and serializes the data in the body.

Because this is an Angular single-page application, rather than using Django’s templating, I’m making calls to a web-based API (implemented in Django). I use a simple helper class for the repetitive task of extracting POSTed data, converting it to Python objects, and validating it.

I made a simple change to this object, and voilà — Django started receiving AngularJS data.

# CONTEXT:
# This function extracts the received data and
# returns it as a Python dict.
if  'CONTENT_TYPE' in request.META and request.META['CONTENT_TYPE'].startswith('application/json'):
    return json.loads(request.body)
elif request.method == 'POST':
    return request.POST.dict()
elif ...

Updates

2014-02-21
Fixed bug in sample code.
Posted in Programming | Tagged , , , , | Leave a comment

Initializing Objects with $.extend()

If jQuery is available, $.extend() can be useful “quick and dirty” method for initializing an object with defaults, while allowing for the caller to provide values to override the defaults.

The advantage is simplicity. One disadvantage is that there is no checking of arguments. The particular situation will drive the relative importance of each.

 

Posted in Uncategorized | Leave a comment