Google+

Sunday, September 22, 2013

9 Step-By-Step How-to add an AngularJS Controller

         By Carmel Schvartzman


In this tutorial we'll learn How-to create an AngularJS Controller, in order to display data on a View. In the previous tutorial we linked the View that we just designed,  with a Controller using a Module  in our AngularJS Blogs Application.  You can follow this step by step tutorial as a standalone, or you can learn all the posts to build the entire app. This is the STEP 9 in this walkthrough to design an end-to-end AngularJS client MVC app.

In the MODEL-VIEW-CONTROLLER architecture of AngularJS, a VIEW is related to a MODEL in the configuration step of the AngularJS app live, when we link it to some CONTROLLER.
This linking action is set in a Module, with the function of declaratively set how the AngularJS app should be bootstrapped. It's like the Main method in a program, setting the instantiation of the application.
Because AngularJS is based on the Dependency Injection paradigm, here is the place to configure the app injecting the functionality that we'll need.

In short, a Controller is the Javascript code that stands behind a View; its functionality is to build the data MODEL and to publish it to the HTML template we call View. That is attained using the $scope directive.


  1. Go to the .JS file, where we just added a AngularJS Module, and create a Javascript var as follows: 



          Call your Controller as you wish, but as a convention we'll prefer an "Ctl" appended to the name. Notice that we must respect the previous Configuration declaration that stated the name of the controller (see the snapshot).
2. Our Controller will get an "$scope" parameter that we'll use to connect data Model to View:



3. In the previous tutorial, we added a View to our application, named "BlogList.html". In that view, we publish the title of the blog using the standard AngularJS "{{ }}" notation, as follows:

And now, at the Controller, we'll initialize that variable with a string:



Notice that we just added an attribute to the $scope. That's all. And the $scope will be used at the View.

4. Let's see how it looks like. Right-click the Index.html and press "View in Browser" (Notice we won't select the BlogList.html file, because it's just a template):


You will see the Blog Title in the rendered html . That was a perfect separation between Data Model and View presentation markup.


That's all!! 
Happy programming.....


כתב: כרמל שוורצמן

No comments:

Post a Comment