Angular JS Favourites/Favorites – Conditional CSS classes

Last few weeks at work I have been trying out Angular JS. First of all, because it is fun and useful to try out new stuff. Secondly because after working with Backbone/Marionette for a few months some things felt that they could’ve been done better. So whilst working on a big Backbone/Marionette project I started looking at Angular a bit.

I’ll just show you some of my favourite features. We are building an app that needs to play, stop, pause etc much like a video player. But we need to do quite a bit more than that. I’ll highlight two features that really helped out clear out some old jQuery blah blah. Maybe I’ll write some more on my favourites coming week.

Conditional CSS classes:

One thing that I kept running into is having to decide when to use a jQuery handler or a Backbone built-in function to toggle a CSS class. This sounds trivial, and maybe it is, but this is such a common feature in a interactive client, that it is a relief to see it handled nicely.

Inline coupling of DOM element and javascript function:

I know, I know this is done in almost any MVC framework. But I just like the way Angular has set this up. Just add HTML attribute ng-click="nameoffunction()" and the $scope.nameoffunction function responds to this. Example below clarifies both Conditional CSS classes and click-handler.

Example play and stop button.:

<div ng-controller="RemoteControl"> 
  <a id="btn-play" class="btn" ng-class="{active: isPlaying}" ng-click="play()">
    <i class="icon-play"></i>
  </a>
</div>
app.controller("RemoteControl", ["$scope"], function($scope){
   $scope.isPlaying = false;

   $scope.play = function() {
      if ($scope.isPlaying) {
        // if already playing turn it off.
        $scope.isPlaying = false;
      } else {
         // do stuff involved with play
         // switch isPlaying to true
         $scope.isPlaying = true;
      }
   }
}]);

Next week I’ll make some time to discuss Directives.


Words by fritzvd

comments powered by Disqus