Snippet of AngularJS for data models

AngularJS Hackathon

AngularJS Hackathon (Photo credit: fumi)

Evil Trout has a blog post comparing AngularJS to EmberJS and one of the examples seems off from what I understand so far about AngularJS. It’s in the section, “What’s wrong with JavaScript primitives as models?” where the concept of the model is compared.

The example in the blog post seems off only because Evil Trout is astounded that AngularJS lets you use plain JavaScript objects as models. If you want to add an observer to a property, you have to do it yourself, Angular won’t do it for you. EmberJS provides an Object class that can be extended, which isn’t a plain JavaScript object.

This can cause maintainability nightmares down the road. Over time, in a large software project, you will inevitably want to replace something that was previously a primitive with a method. In Ember you can do this painlessly; in AngularJS you’ll have to update every template where that model is used.

That’s your own fault if you aren’t using a getter/setter pattern in AngularJS. As my example shows, you don’t have to worry much since when you’re updating the model presumably it’s attached to a $scope in a controller. Thus, the controller’s $scope can  watch the model for updates.

Here’s some code on JSFiddle showing how I would implement a Room model. When the width and height change, the area property is updated in the controller.

3 Comments to Snippet of AngularJS for data models

  1. […] Snippet of AngularJS for Data Models […]

  2. […] Snippet of AngularJS for data models […]

  3. […] Snippet of AngularJS for data models […]