Google+

Saturday, August 17, 2013

AngularJS Step-By-Step How-to create a Controller



  1. AngularJS allows us to create sites on the MVC approach, that means, respecting a marked distinction between the MODEL-VIEW-CONTROLLER in CLIENT side. In this tutorial we'll create an AngularJS controller - using the  NG-CONTROLLER attribute:
  2. Create an HTML page, and add the reference to the AngularJS script (download it from http://docs.angularjs.org/misc/downloading):
    <script type="text/javascript" src="angular.js"></script>
  3. Add a DIV to the BODY block:

    <div>

    </div>
  4. Add the following attribute the the DIV tag:

    <div ng-controller="MyCtl">

    </div>

    This way we tell to the AngularJS engine that this DIV is a controller named "MyCtl".
  5. Now let's say we want to display a custom text inside a h1 tag. This text won't be hard coded in the html, instead it will comes from the CONTROLLER to our html VIEW. So let's add the h1 tag and the "{{ }}" which tell the engine to bind to the data:

    <div ng-controller="MyCtl">
       <h1>{{  }}</h1>
    </div>
  6. Inside the {{}} block we'll insert the name of the property to bind and the string   " - Home Page" :

    <div ng-controller="MyCtl">
       <h1>{{  data.myText + " - Home Page" }}</h1>
    </div>
  7. Finally, to force the AngularJS engine to parse our html page, we add to the BODY tag the following attribute:
    <body ng-app="">
  8. For the sake of making a clear distinction between VIEW (html) and MODEL , we'll add a .js file and the corresponding reference to our html page:

    <script type="text/javascript" src="myController.js" />
  9. And in the .js page:

    function MyCtl($scope){
       $scope.data = { myText : "Welcome to my First AngularJS Project " };

    }
  10. Take a look to this code: the name of the function must be exactly the same of  your controller(MyCtl).
    Also, the controller gets an "$scope" parameter, and we add the attribute called "data" to it(you can call it whatever you want). This object will be a JSON object containing the property "MyText", which is a string.
  11. That's it!! Back to our html page, refresh it and you'll see the complete message in your screen.

No comments:

Post a Comment