AngularJS: Filter – Behind the Scenes

AngularJS comes with a ton of built in features to help us out – meaning we don’t have to reinvent the wheel every time we want to do something. This makes it extremely easy to do things such as searching or filtering. However, sometimes it’s a good idea to check what’s going on under the hood, which can only help us in the end. These helpers are great, but if you’re knew to programming, they could stunt your growth as a developer. So let’s dive in.

I built an app called Medidate. It’s a simple (a lot of hours goes into simple!) single page app that keeps track of meditation sessions: the date, which kind of meditation, and the duration. It uses Rails as an API on the back-end and AngularJS on the front-end. I’m going to go over a sorting feature that could easily be implemented with Angular’s built in Filter helper. Here’s a Plunker with the easy way.

The Easy Way

Here’s some of the code…

    <div ng-controller="UsersController as vm">
      <div class="container">
        <div class="col-md-3 col-md-offset-9 dropdown-meditation">
          <div class="button-group">
            <select class="btn btn-default btn-md dropdown-toggle dropdown-text"
              ng-model="vm.option">
              <option value="" disabled selected>Sort Events By</option>
              <option value="date">By Date (Asc)</option>
              <option value="-date">By Date (Desc)</option>
              <option value="meditation.name">By Meditation</option>
              <option value="minutes">By Minutes</option>
            </select>
          </div>
        </div>
        <br>
        <div ng-repeat="event in vm.user.events | orderBy: vm.option">
          <p style="text-decoration: none">{{event.date | date: medium}} for {{event.minutes}} minutes &mdash;
        {{event.meditation.name}}</p>
        </div>
      </div>
    </div>

To give a bit of background, the information that’s being sorted here is an array of user events. The user has many events, which have the date, minutes, and a nested association of meditation, with id and name. This was all produced from an $http call to the back-end which was serialized into JSON by active model serializer – a very helpful gem for Rails.

Notice the dropdown and how we’re listing the options. The values of the options are bound to vm.options. All we have to do is declare vm.option = ” in the controller and when the dropdown is selected, vm.option will now be bound to the selected option. This will in turn set the filter in the ng-repeat. Notice the orderBy : vm.option that is declared in the repeat. This is the aforementioned built in magic of Angular. Whichever option is selected in the dropdown will change the orderBy option and effect how the list is ordered.

But what happens when you’re asked how it works. You know, like if someone asked you the what happens when you press the gas pedal in your car?  I don’t know, it just goes!

This is when it gets interesting. Getting your hands dirty.  Instead of using filter in the ng-repeat as above, we’re going to leave ng-repeat alone, with no orderBy filter! The hard work is going to be done in the controller. Check it.

The Hard Way

Here’s the  dropdown and ng-repeat…

    <div ng-controller="UsersController as vm">
      <div class="container">
        <div class="col-md-3 col-md-offset-9 dropdown-meditation">
          <div class="button-group">
            <select class="btn btn-default btn-lg dropdown-toggle dropdown-text"
                    type="button" 
                    ng-model="vm.selectedOption"
                    ng-change="vm.sortBy()" 
                    ng-options="option for option in vm.options">
              <option value="" disabled="" selected="">Sort Events By</option>
            </select>
          </div>
        </div>
        <br>
        <div ng-repeat="event in vm.user.events">
          <p style="text-decoration: none">{{event.date | date: medium}} for {{event.minutes}} minutes &mdash;
        {{event.meditation.name}}</p>
        </div>
      </div>
    </div>

In the dropdown above, ng-model is set to vm.selectedOption. Now whenever the user selects an option from the dropdown, the model is now bound to the option from ng-options. The options are declared in the controller which we’ll be taking a look at soon. The straw that stirs the drink is ng-change, which fires the vm.sortBy function in the controller. Let’s take a looksie.

.controller('UsersController', [function() {
      
      var vm = this;
      vm.sortBy = sortBy;
      vm.sortDate = sortDate;
      vm.sortMeditation = sortMeditation;
      vm.sortMinutes = sortMinutes;
      
      vm.options = ["Date (Asc)", "Date (Desc)", "Meditation", "Minutes (Asc)", "Minutes (Desc)"]

      function sortBy() {
        if (vm.selectedOption === vm.options[0]) {
          vm.sortDate();
        } else if (vm.selectedOption === vm.options[1]) {
          vm.sortDate();
          vm.user.events.reverse();
        } else if (vm.selectedOption === vm.options[2]) {
          vm.sortMeditation();
        } else if (vm.selectedOption === vm.options[3]) {
          vm.sortMinutes();
        } else if (vm.selectedOption === vm.options[4]) {
          vm.sortMinutes();
          vm.user.events.reverse();
        }
      };
 
// more code below

I like to bind my functions up top so I can see exactly what’s going on in the controller. This way I don’t have to search through hundreds of lines of code. Also, now we can just go ahead and write the functions as declarations, not expressions, which will save us from any hoisting headaches.

Like I said before, when the option is selected from the dropdown, that option is now assigned to vm.selectedOption and the vm.sortBy function fires. In the sortBy function, we’ll check to see which option was assigned to selectedOption and then fire a corresponding function to sort the user.events array. Here are the missing sort functions…

      function sortMinutes() {
        vm.user.events.sort((a, b) => parseInt(a.minutes) - parseInt(b.minutes))
      }

      function sortDate() {
        vm.user.events.sort((a, b) => (new Date(a.date)) - (new Date(b.date)));
      }

      function sortMeditation() {
        vm.user.events.sort((a, b) => {
          if (a.meditation.name < b.meditation.name) {
            return -1;
          } else if (a.meditation.name > b.meditation.name) {
            return 1;
          } else {
            let dateA = new Date(a.date);
            let dateB = new Date(b.date);

            if (dateA > dateB) {
              return 1;
            } else if (dateA < dateB) {
              return -1;
            } else {
              return 0;
            }
          }
// end of UsersController

Each function handles the data based on what the value is. Because the data in the user.events array are strings, we’ll have to convert them before sorting. The sortMinutes function is dealing with numbers which forces us to parseInt() the strings to integers. Same thing goes for the sortDate function, which we have to convert to a date before it can be sorted. Last is the sortMeditation function which takes the nested association – meditation – and sorts by name. Here we’re returning a negative 1 if the a is less, positive 1 if the b is less, and then instead of a zero if the names are the same, we’re using a sub-sort, which sorts by date.

Here’s a working plunker of the non-magic Angular filter. I think it’s cool to look under the hood sometimes and see what all the magic is about. You never know if you’re going to learn something new – I know I did! Leave a comment below if you have any questions. Thanks for reading!
 

 

 

Advertisements