Friday, April 19, 2013

Things I Love About Angular.js: Common Things are Easy


One of the greatest things about Angular.js is the amount of things you're able to do without writing any javascript. Take, for example, editing an array of objects. When I started with angular, my code looked like this.

Now, I know I can do this.


Now, I the neat-freak in me cringes about the "1" in the splice call... I feel like I'm not using it the way it was meant to be. The functional programmer sighs about the destructive operation. The worrier wonders if this is a slippery slope to "OMG CODE EVERYWHERE!" style coding that would make even novice PHP programmer blush. Avoiding that requires balance—use this sparingly and only when it helps make things clear.

But, when it comes down to it, it's less code than before and there's no place for subtle inconsistencies to hide in all of the forms I have that require manipulating arrays of objects. If it's idiomatic, then at least it's easily recognizable for what it is: a simple solution to a problem that pretty much any form of any complexity has to solve.

1 comment:

  1. Andrew - Great that you are deep into SPA and AngularJS and eager to share your findings with everyone. I can't seem to resist commenting on this particular post ... because it recommends a practice with which I strenuously disagree: performing a raw JavaScript operation in the HTML.

    This is almost never a good idea ... not even as a short-term work around. It violates a fundamental Angular maxim: "no JavaScript in the view; no HTML in the controller".

    This is practical advice, not just some bumper sticker for purists.

    Consider your delete example: <button ng-click="dudes.splice($index,1)">Delete</button>

    When could this ever be a good thing? Let's start with functionality. In any application of consequence, to delete something requires more than removing it from a list, particularly if that thing is persisted. Separation of Concerns? I shouldn't be forced to change the HTML if the business logic behind "delete" changes. Testability(another Angular fundamental)? You can't test this except with E2E tests. As it stands, "add" and "delete" are completely invisible to the controller so there is no way you can test their effects on the controller and its behavior. Productivity? Negative. It is only slightly quicker to add this code to the HTML than to add it to the controller and bind to it; add the future costs of reading and maintaining this kind of code and you have set course for declining velocity.

    The same goes for your "add" suggestion.

    Folks, just don't do this ... ever. Put "add" and "delete" logic in the controller where they belong. Period.

    ReplyDelete