3 ways to create a Controller in Angular

Creating the controller when adding it to the module

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

        app.controller('UsersController', function ($scope) {
            $scope.userProfiles = [
                { "id": 1, "Name": "Peter", "Age": 21 },
                { "id": 2, "Name": "Alex", "Age": 22 },
                { "id": 4, "Name": "Andrew", "Age": 53 }
            ];
        });

When we add a Controller to the module we set a name for the Controller and the controller, we can just define the Controller at that point, giving the full object as an input.

Creating the controller at a place and assigning it to the module later

        var app = angular.module('BasicApp', []);
        app.controller('UsersController', UsersController);

        function UsersController($scope) {
            $scope.userProfiles = [
                { "id": 1, "Name": "Peter", "Age": 21 },
                { "id": 2, "Name": "Alex", "Age": 22 },
                { "id": 4, "Name": "Andrew", "Age": 53 }
            ];
        }

Creating the controller in some other place and assigning the Controller’s function name as a pointer will allow to do the same.

Creating the controller in an array of controllers and giving it to the module

        var controllers = {};
        controllers.UsersController = function($scope) {
            $scope.userProfiles = [
                { "id": 1, "Name": "Peter", "Age": 21 },
                { "id": 2, "Name": "Alex", "Age": 22 },
                { "id": 4, "Name": "Andrew", "Age": 53 }
            ];
        }
        controllers.SecondController = function ($scope) { }


        var app = angular.module('BasicApp', []);
        app.controller(controllers);

This way we just create an array with one or more controllers and assign them as properties of that object, then, we can just assign the array object to the module. You can also combine this with previous approach creating the controllers on a different place, assigning them to the array using pointers and finally assigning the array, something like this:

        function UsersController($scope) {
            $scope.userProfiles = [
                { "id": 1, "Name": "Peter", "Age": 21 },
                { "id": 2, "Name": "Alex", "Age": 22 },
                { "id": 4, "Name": "Andrew", "Age": 53 }
            ];
        }
        function SecondController($scope) { }
        function ThirdController($scope) { }
        
        var controllers = {
            UsersController: UsersController,
            SecondController: SecondController,
            AnotherController : ThirdController
        };
        
        var app = angular.module('BasicApp', []);
        app.controller(controllers);

Quite elaborate maybe, but just as an idea.

One thought on “3 ways to create a Controller in Angular

Leave a Reply

Close Bitnami banner
Bitnami