March 10, 2015

Controllers in AngularJS

Controllers in AngularJS

Controllers are one of the central pieces of Angular framework. While working in angular your going to create multiple controllers. As the name implies controllers are in-charge of area of an application. With angular, controllers are in-charge or responsible for building a model.

A model contains the data we need to work with and the controller will do whatever it needs to grab that data. So it might need to make some calculations or call back to a web server that talks to the database, whatever it takes.

I'll show you how to build a controller that is able to build a model and we will be able to use data binding to show that model in a view. The view is our html webpage.

Controller Basics:

The job of the controller is to control the information that we put on a page or in an editing scenario to save the information that the user is typing into the page. To bring a controller to live the first thing you see is directive ng-controller

ng-controller is an attribute that we place into our html. When we use ng-controller we can specify the name of the controller to take control some of the area in html.

<div ng-app>
   <div ng-controller="MainController">
   .
   .
   .
   </div>
</div>

ng-controller can only be used where we have ng-app in place and we have to tell angular the name of the controller that will be in-charge In this case it is MainController. We have to name these controllers because in large applications dozens and dozens of controllers will be used.

We need to create a controller with that name to target the controller in an html. We can do this by creating a function and assigning that function to a variable with the matching name.

var MainController = function($scope) {
   $scope.message = 'Hello World!';
};

We don't invoke these functions, angular will invoke these controller function when it needs to create a controller to manage an area in a webpage. When angular creates a controller it can pass a parameter to the function. A parameter called $scope with a dollar sign in front. Just like the ng prefix the dollar($) sign prefix is a sign that the component your working with is a component provided by angular. What we can do with the $scope argument is attach model to the object. Dollar($) sign is not a model, the things that are attached to the scope are model. In the above code snippet we have attached a single property to scope called message which points to the string 'Hello World!'. This will make message available to us inside the html so that we can data-bind it into the display.

<div ng-app>
   <div ng-controller="MainController">
      <h1>{{message}}</h1>
   </div>
</div>

Modules:

The controller we have been creating is in a global name space which is usually bad. When your building your own application with angular you probably don't want to do this. So we build our controllers inside a module. My goal is to create an angular module as a home for my controller and then i can have many different controllers in that same module. You can even have multiple modules for an application. This all depends how complex your application is.

var app = angular.module('NameOfModule', []);

var MainController = function($scope, $http) {
   //...
};
app.controller('MainController', MainController);

Conclusion:

All together i am going to show you an example which includes controller, $scope, $http, modules. I am going to use API from github to get the user information and display it in html.

HTML

<div ng-app="GetUserInfo">
  <div ng-controller="MainController">
    <div>{{error}}</div>

    <div>{{user.name}} from {{user.location}}</div>

    <img src="{{user.avatar_url}}" title="{{user.name}}">    
  </div>  
</div>

JavaScript

(function() {
    var app = angular.module('GetUserInfo', []);

    var MainController = function($scope, $http) {

        var onUserComplete = function(response) {
            $scope.user = response.data;
        };

        var onError = function(error) {
            $scope.error = 'Failed to fetch';
        };

        $http.get('https://api.github.com/users/vivinantony')
            .then(onUserComplete, onError);

    };

    app.controller('MainController', ['$scope', '$http', MainController]);
}());

Attachments:

We have to use this attachment to make AngularJS work.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.5/angular.min.js"></script>
demo

No comments:

Post a Comment

Popular Posts

Views