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.
[…] so after checking how the basics of Angular work on a single page and the different ways to create a controller in Angular it’s time to do what angular is meant to do: create a client’s side application that […]