Angular.js

New Features in AngularJS 1.3

Now that Angular 1.3 has been officially released, I thought I would talk about some of the new features that developers would like to know, to include:

  • Performance improvements
  • One-time bindings
  • ngModel.$validators
  • ngMessages
  • ngModelOptions

If you are still using IE 8 as your main browser, first I want to say WHY? Angular 1.3 is dropping support for this old browser. So if you are still using it, then Angular 1.3 may not work for you.

Let’s talk about the cool new features starting with performance.

Performance

Angular 1.3 provides a boost in performance versus the previous versions. The Angular development team concentrated on making it less overhead. According to Jeff Cross and Brian Ford at the Ng-Europe conference, they achieved 4.3 times faster DOM manipulation with 73% less garbage and 3.5 times faster digest with 87% less garbage versus 1.2.0 version based on their largetable benchmark tests.

To help increase performance of your application, a new production mode is available. This mode will turn off features that mainly are used for debugging purposes. Add the following line to your application to enable this feature:

$compileProvider.debugInfoEnabled(false);

When using the http service, to prevent digest from being triggered every time, the following command will combine a group of short http calls to a single digest:

$httpProvider.useApplyAsync(true);

One-Time Binding

One of Angular’s best features is the automatic two-binding that you get with the model.

There is a memory and overhead cost for using this feature, but if your data is static and does not need to be updated, then use the new one-time binding. Here is an example:

<tbody>
	<tr ng-repeat='book in ::books'>
		<td>{{::book.title }}</td>
		<td>{{::book.author}}</td>
		<td>{{!book.availability ? 'Yes' : 'No'}}</td>
	</tr>
</tbody>

You probably notice some new notation in the Angular expression. The ‘::’ identifies that this is a one-time binding to Angular. The list of books, the title, and the author will not change, but the book’s available status can update.

ngModel.$validators

Forms now have validators that are tied to the model, $ngModel.$validators. They can be called in both directions of the binding. Create a directive that asks for ngModel and then add new validation function that returns a boolean. When the validator returns false, it will mark the property as $error. Check the example below:

.directive('checkTitle', function() {
    return {
      restrict: 'A',
      require: 'ngModel',
      scope: {
        testBooks: '=checkTitle'
      },
      link: function(scope, element, attributes, ngModel) {
        ngModel.$validators.checkTitle = function(modelValue) {
          return _.findIndex(scope.testBooks, { 'title': modelValue }) == -1;
        };
        scope.$watch('testBooks', function() {
          ngModel.$validate();
        });
      }
    };
  })

There is also asyncValidators for when you need to call an http service to check the validity. A promise will be delivered to set the validation status when the http request has completed. All the asynchronous validators must return before the status is updated.

.directive('checkAuthor', function($q, $http) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attributes, ngModel) {
        ngModel.$asyncValidators.checkAuthor = function(modelValue) {
          $http.get('/api/author/' + modelValue)
                then(function resolved() {
                        return $q.reject('exist')
                }, function rejected() {
                        return $q.resovle();
                });
        };
      }
    };
  });

ngModelOptions

A new directive called ngModelOptions provides list of events that will be triggered while updating the model.

updateOn – A event string name telling the model what input to bind. This allows you to bind to blur event or any other valid event.

<input type='text' name='author' class='form-control' ng-model='book.author' ng-model-options='{ updateOn: 'blur' }'/>

debounce – A delay in milliseconds before the model is updated. A use case for this feature would be preventing a search to backend service until the user finishes typing.

<input type='text' name='title' class='form-control' ng-model='book.title' ng-model-options='{ debounce: 1000 }'/>

getterSetter – This allow functions bound to ngModel to be treated as getter and setters. A function called with zero arguments returns the value and the function called with one argument sets the value.

<input type='text' name='description' class='form-control' ng-model='book.description' ng-model-options='{ getterSetter: true }'/>
<div><small>{{book.description()}}</small></div>

ngMessages & ngMessage

Another new directive ngMessages allows for displaying message to users. This directive will simplify code that once had complex if statements to show a single message. Instead of if statements, ngMessage directive is processed in the order they are listed.

Look at the following example:

<form name='addBookForm' novalidate='' ng-submit='addBook(addBookForm.$valid)'>
          <div class='form-group'>
            <label>Title</label>
            <input type='text' name='title' class='form-control' ng-model='book.title' required='' ng-minlength='3' ng-maxlength='50' check-title='books'/>
            <div ng-messages='addBookForm.title.$error' ng-messages-include='error-messages.html'></div>
          </div>
		</div>
        </form>

error-messages.html
<div class='errors'>
  <div ng-message='required'>This field is required.</div>
  <div ng-message='minlength'>Field is less than 3 characters.</div>
  <div ng-message='maxlength'>Field is greate than 50 characters.</div>
  <div ng-message='checkTitle'>Duplicate title.</div>
  <div ng-message='checkAuthor'>Enter first and last name of author.</div>
</div>

In this example, the required message is processed first and the minlength.

Final Thoughts

This is just a sample of some of new features that are part of Angular 1.3 release. Check out the Plunk site to view the features in a working environment.

I would recommend also reading the official documentation to learn all the new features and to see more details on the items I have already discussed.

Reference: New Features in AngularJS 1.3 from our WCG partner Keyhole Software at the Keyhole Software blog.

Keyhole Software

Keyhole is a midwest-based consulting firm with a tight-knit technical team. We work primarily with Java, JavaScript and .NET technologies, specializing in application development. We love the challenge that comes in consulting and blog often regarding some of the technical situations and technologies we face.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button