Thursday 20 June 2013

Angular JS - Almost the simplest thing you can do

While Angular lets you build very complex applications it also lets you do very simple things, the simplest of which is to bind data to a model. You do this by using templates. Templates allow you to output data, carry out calculations in-line. Taken from the AngularJS docs:

  • Attribute Evaluation: evaluation of all properties are against the scope, doing the evaluation, unlike in JavaScript where the expressions are evaluated against the global window.

  • Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, where trying to evaluate undefined properties can generate ReferenceError or TypeError.

  • No Control Flow Statements: you cannot do any of the following in angular expression: conditionals, loops, or throw.

  • Filters: you can pass result of expression evaluations through filter chains. For example to convert date object into a local specific human-readable format.

Templates are simple to use, like this:
{{3 + 3}}

However this is not particularly interesting in and off itself, we are simply displaying data. To make this both more interesting and useful we'd like ability to dynamically grab dats from the user and then update the page using that data, this is where two-way binding comes in.

Two way data binding can be added to elements on the page. This binding allows data to be entered into one element and the value of that data to be reflected back through other elements on the page. To do this an input element is annotated with an ng-model attribute. This attribute specifies the name of the 'model' that the data will be stored in. As data is entered into the element Angular will update the model with this data. The value of this model can then be displayed using the 'moustache' syntax in a template as seen above.

{{3 + 34}}

Hello {{name}}

If a user enters the value 'Kevin' into the input field then the following is produced:

Simpledatabinding

The key thing here is hg-model, this creates a model called 'name' which is then available to be used in the rest of the page, in this case inside the h2 tag. ng-model (aka ngModel) takes a string value which specifies the name of the model that Angular binds the data to.

Data-binding is a general purpose mechanism. This means that you can bind the data to other places in the DOM such as a class name or a attribute value.

No comments:

Post a Comment