In the previous post, we began our journey with the introduction to the basics of Angular. In this post however, we will continue that journey by introducing Controllers into the picture.
If you have gone through the previous blog posts, where we’d talked about the MVC architecture, you should know what a controller basically is. If you didn’t, I would suggest you to have a look at this post before continuing.
So, we begin with a simple regular Angular Skelton.
With this in place, we can begin with creating controller and writing some javascript. To add controller to the view we do the following.
The controller Technology is basically a JavaScript's function, with the $scope object as parameter. We will be talking about $scope object a lot in later posts. Our controller will look something like.
If you look closely, we have defined a collection technologies, in the $scope object, which can be accessed from the View (HTML) directly. Since it’s an array we need to loop though in order to display it on the screen.
On running the code, the output will be the following.
Here is the entire HTML:
1: <!DOCTYPE html>
2: <html ng-app>
3: <head>
4: <title>Angular Demo</title>
5: <script src="js/angular.js"></script>1:
2: <script src="js/viewmodel.js"></script>
6: </head>
7: <body ng-controller="Technology">
8: <ul>
9: <li ng-repeat="technology in technologies">
10: {{technology.technologyName}}
11: </li>
12: </ul>
13: </body>
14: </html>
JavaScript Code:
1: function Technology($scope){
2: $scope.technologies =
3: [{technologyName: 'HTML5'},
4: {technologyName:'.Net'},
5: {technologyName:'JAVA'}];
6: }
Hope you’d like the post. Stay tuned for more.
0 comments