Wednesday 23 July 2014

Angular JS - Expression and directives

Expressions are used in Angular JS for outputting html. Expression are written inside double curly braces. " {{ expression }}".  Directives are used to extend HTML with new attributes, the directives are prefixed by "ng-".

Example 1 - Using expressions:

<div ng-app="" ng-init="quantity=3;cost=10;">

   <p>Total: {{quantity*cost}}</p>   

 <p>5 + 5 is {{ 5+5 }}</p> 

 <p>'K' + 'ing' is {{'K'+'ing'}}</p>

  </div>



AngularJS views blend information from the model into a HTML layout. You utilize AngularJS directives to define AnguluarJS how to blend the information into the HTML format. This content will cover the most regularly utilized AngularJS directives.

Interpolation Directive

The interpolation directive standout among the most basic directives in AngujarJS. The interpolation directive embeds the output of an expression into the HTML layout. You check where to embed the expression making use of the {{ }} symbols.

<div ng-controller="HelloController" >
      <span>{{helloData.msgfun()}}</span>
</div>


<script>
    angular.module("myapp", [])
    .controller("HelloController", function($scope) {
      $scope.helloData = {};
      $scope.helloData.msgfun= function() { return "A text from a function"; };
    });
</script>


In the example {{helloData.msgfun()}} is the interpolation directive which calls the 
helloData.msgfun() function on the model object.

There is one alternative for the interpolation called ng-bind. It uses 'ng-bind' attribute to the html were the data to be inserted. For example, considering the above case:

<div ng-controller="HelloController" >
      <span ng-bind="helloData.msgfun()"></span>
</div>

Some may feels like using innerHTML in JavaScript.

There are lots more directives available in Angular JS to get familiar with in my upcoming posts.

Hope you are ok with the example. Your feedback is always accepted. Many thanks.

No comments:

Post a Comment