- 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:
- 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>
- Add a DIV to the BODY block:
 <div>
 </div>
- 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".
- 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>
- 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>
- Finally, to force the AngularJS engine to parse our html page, we add to the BODY tag the following attribute:
 <body ng-app="">
- 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" />
- And in the .js page:
 function MyCtl($scope){
 $scope.data = { myText : "Welcome to my First AngularJS Project " };
 }
- 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.
- That's it!! Back to our html page, refresh it and you'll see the complete message in your screen.
Saturday, August 17, 2013
AngularJS Step-By-Step How-to create a Controller
Subscribe to:
Post Comments (Atom)
 
No comments:
Post a Comment