Sunday, July 14, 2013

AngularJS inbuilt directives

This post will give introduction about different tags(directives) available in Angular.

In this post we will be focusing on -
ng-include
ng-repeat
ng-controller
ng-view

ng-include-
Using ng-include tag we can fetch any external HTML file in our current HTML. Just like script tag where we can include external javascript file, in the similar way using ng-include we can include external html file as well. This HTML will be embedded into our original html itself.
Ex. - <div ng-include src="'view/menu.htm'" ></div>

ng-repeat-
This is equivalent to traditional foreach loop. Using this directive you can write a foreach loop in HTML as well. Generally we write ng-repeat on a collection. We take the each values of collection and repeate the underlying tag.
Ex . -
<ul ng-repeat="items in itemArray">
<li>
   <div>{{item.name}}<div>
</li>
</ul>

itemArray should be defined in the controller scope. The above code traverses on itemArray and repeat the "ul" tag with every value and populate the name property of item in the mentioned Div element.

ng-controller -
ng-controller is a directive by which angular supports the idea of code behind for MVC implementation.(There are alternative ways possible to define controller, but this is the simplest and popular way to define controller).
Here is the example from Angular official site -
The above diagram gives very simple view of how controller, view and scope are related. controller is defined in view with ng-controller directive and the corresponding scope is available in the function "MyCtrl".  Once Angular checks this directive in the HTML it looks for corresponding definition in the JavaScript and injector take cares of mapping the scope, view and controller.

ng-view-
This tag is very usefule once we write single page application using routing framework provided by Angular. We wont go into the detail of routing framework, but its more of the mechanism in which once you change the url, the corresponding view (defined in configuration) gets loaded automatically. This view render happens inside this ng-view tag only. It is very much similar to MVC ASP .NET app, where you hit the controller and the corresponding view get renders.
Ex. - available here - http://docs.angularjs.org/api/ng.directive:ngView

2 comments:


  1. Angular’s Controllers hold the representation of the knowledge—the traditional model— and also act as the link between the user and the system. While the UI is automatically updated by using bidirectional binding to the $scope, Angular doesn’t provide a convention to represent richer models, other than assigning POJOs and functions to it: Basically, static properties.
    More Information: AngularJS Training in Chennai

    ReplyDelete

  2. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ..Best Angularjs Training in Chennai|Angularjs Training in Chennai

    ReplyDelete