AngularJS controllers are JavaScript functions that are responsible for managing the behavior of a view. They are used to interact with data models, manipulate data and provide a logical structure to your application. Controllers are defined in AngularJS using the controller() function of the module object.

Controllers in AngularJS

Here’s an example of a straightforward AngularJS controller:

HTML:

<div ng-controller="myController">
  <p>{{ message }}</p>
</div>

JavaScript:

var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
  $scope.message = 'Hello World';
});

In this example, we have defined a controller named “myController” which is associated with the div element using the ng-controller directive. The controller function takes a $scope parameter, which is an object that contains the data that will be used in the view. In this case, we have a message property on the $scope object that is set to “Hello World”. The message property is displayed in the view using an AngularJS expression {{ message }}.

You can define multiple controllers in your application, each with its own responsibilities and data. Here’s an example of a controller that uses an AngularJS service to fetch data from an API:

HTML:

<div ng-controller="myController">
  <ul>
    <li ng-repeat="user in users">{{ user.name }}</li>
  </ul>
</div>

JavaScript:

var app = angular.module('myApp', []);
app.controller('myController', function($scope, $http) {
  $http.get('/users').then(function(response) {
    $scope.users = response.data;
  });
});

In this example, we have defined a controller named “myController” which uses the $http service to fetch a list of users from an API endpoint. The get() method of the $http service returns a promise which is resolved when the data is fetched from the API. Once the promise is resolved, the then() method is called, which updates the $scope.users property with the fetched data. The data is then displayed in the view using the ng-repeat directive.

Scope of AngularJS

In AngularJS a scope is a special object associated with the application model. Panes act as a bridge between controllers and views, allowing them to communicate with each other.

Here’s an example of how the scope is used in AngularJS:

angular.module('myApp', [])
    .controller('myController', function($scope) {
        $scope.message = 'Hello, World!';
    });

In the above example, we define a new module called myApp and attach a controller to it called myController. The controller function takes an argument called $scope, which is the scope object. In this example, we set the message property of the $scope object to ‘Hello, World!’.

We can then use this scope in the view by using the {{ }} notation to bind the value of the message property to the contents of a p element, like so:

<div ng-app="myApp" ng-controller="myController">
    <p>{{ message }}</p>
</div>

In the above example, we create a div element with the ng-app directive set to myApp to indicate that this element is part of the myApp module. We also use the ng-controller directive to bind the myController controller to this element. Finally, we use the {{ }} notation to bind the value of the message property of the $scope object to the contents of a p element in the view.

Filters for AngularJS

AngularJS formats data in views using filters. Filters can format a variety of data kinds, including text, integers, dates, and others.

Here’s an example of how filters are used in AngularJS:

angular.module('myApp', [])
    .controller('myController', function($scope) {
        $scope.price = 1234.56;
        $scope.date = new Date();
    })
    .filter('currencyFormat', function() {
        return function(input) {
            return '$' + input.toFixed(2);
        }
    })
    .filter('dateFormat', function($filter) {
        return function(input) {
            return $filter('date')(input, 'yyyy-MM-dd');
        }
    });

In the above example, we define a new module called myApp and attach a controller to it called myController. The controller function takes an argument called $scope, which is the scope object. In this example, we set the price property of the $scope object to 1234.56 and the date property to the current date.

Controllers in AngularJS

We also define two filters, currencyFormat and dateFormat. The currencyFormat filter takes a number as input and formats it as a currency, with two decimal places and a dollar sign in front. The dateFormat filter takes a date as input and formats it as a string in the format yyyy-MM-dd.

You may incorporate these filters into your views by using |. To apply the (pipe) character to the data, do the following:

<div ng-app="myApp" ng-controller="myController">
    <p>Price: {{ price | currencyFormat }}</p>
    <p>Date: {{ date | dateFormat }}</p>
</div>

In the above example, we use the {{ }} notation to bind the value of the price property of the $scope object to the contents of a p element in the view, and apply the currencyFormat filter to it using the pipe character. We also bind the value of the date property to another p element and apply the dateFormat filter to it using the pipe character.

Services Provided by AngularJS

In AngularJS, services are used to share code and data across different parts of an application. Services are singleton objects that are instantiated once and then shared across all components that use them.

Here’s an example of how services are used in AngularJS:

angular.module('myApp', [])
    .service('myService', function() {
        this.getData = function() {
            return [
                { id: 1, name: 'John' },
                { id: 2, name: 'Mary' },
                { id: 3, name: 'Peter' }
            ];
        };
    })
    .controller('myController', function($scope, myService) {
        $scope.data = myService.getData();
    });

In the above example, we define a new module called myApp and attach a service to it called myService. The service function defines a method called getData, which returns an array of objects containing some sample data.

We then define a controller called myController, which takes two arguments: $scope and myService. The $scope argument is the scope object, and the myService argument is the service that we defined earlier.

In the controller function, we use the myService object to call the getData method and assign the returned data to a data property on the $scope object. We can then use this data in the view by binding it to various elements, like so:

<div ng-app="myApp" ng-controller="myController">
    <ul>
        <li ng-repeat="item in data">{{ item.name }}</li>
    </ul>
</div>

In the above example, we create a ul element in the view and use the ng-repeat directive to iterate over the items in the data array. We then bind the name property of each item to the contents of a li element.

AJAX in AngularJS – $http

In AngularJS, the $http service is used to make AJAX requests to a server and retrieve data in JSON or other formats. It is a core service of AngularJS and is typically used within a controller or other components to interact with a server-side API.

Here’s an example of how to use the $http service to make a GET request:

app.controller('myController', function($http, $scope) {
  $http.get('/api/users')
    .then(function(response) {
      $scope.users = response.data;
    }, function(response) {
      console.log('Error retrieving users: ' + response.statusText);
    });
});

In this example, we have defined a controller named “myController” which uses the $http service to make a GET request to the URL /api/users. The get() method of the $http service returns a promise which is resolved when the data is fetched from the API. Once the promise is resolved, the then() method is called, which updates the $scope.users property with the fetched data. If there is an error while making the request, the error() method is called and an error message is logged to the console.

Here’s an example of how to use the $http service to make a POST request:

app.controller('myController', function($http, $scope) {
  $http.post('/api/users', { name: 'John', age: 30 })
    .then(function(response) {
      console.log('User created successfully');
    }, function(response) {
      console.log('Error creating user: ' + response.statusText);
    });
});

In this example, we have defined a controller named “myController” which uses the $http service to make a POST request to the URL /api/users with some data in the request body. The post() method of the $http service returns a promise which is resolved when the request is successful. If there is an error while making the request, the error() method is called and an error message is logged to the console.

Categorized in: