Wednesday 8 October 2014

When to use Braces, and Which Ones to Use


I've been using AngularJs for just over a year now but I think it was a couple of months before I really understood the difference between double and single braces, when to use them, and when not to use them at all. Although it is in the documentation as you go through, I don't remember seeing it explicitly written anywhere and I found myself randomly trying each thing before things would work. I've still not seen it written explicitly anywhere, so I'm sure that it must still be causing frustration to new AngularJs developers now.

An Expression

An expression is when you want to do something when something else is true. In this case use single braces.

ng-class="{newClass: useNewClass}"

A Value

When you already have a value on the $scope and you just want to write it out then use double braces.

<p>{{myValue}}</p>

A Function Call

When you're calling or passing a function, you don't need to use braces at all.

ng-controller="HeroCarouselController"
ng-click="closeModal()"

Do Something with x

When the directive has a built-in expectation of what to do with a given value, then you don’t need to use braces either.

ng-if="currentIndex == slide.index”
ng-repeat=“item in items"

Anything Else?

If you can think of any other examples that could help others understand, please leave a comment.

No comments:

Post a Comment