AngularJS Controllers | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

AngularJS Controllers

I don't really understand the controllers. Can anybody help me out here?

23rd May 2018, 9:02 PM
Paul Grasser
Paul Grasser - avatar
2 Answers
+ 5
A controller is simply an object where you store methods and variables. When you assign the ng-controller directive you are simply indicating that block in the DOM will have access to the object to use its properties. Consider the following example: index.js: angular.module('app', []) app.controller('myCtrl', ($scope) => { $scope.name = 'Sololearn'; }); app.controller('otherCtrl', ($scope) => { $scope.name = 'This isn't Sololearn'; }); index.html <div ng-app="app"> <div ng-controller="myCtrl"> <h1> {{name}} </h1> </div> <div ng-controller="otherCtrl"> <h2> {{name}} </h2> <div> </div> The first header will show 'Sololearn' since it only has access to the properties defined within the 'myCtrl' object. On the other hand the second header will only show the properties defined inside the object 'otherCtrl' (that is 'This isn't Sololearn') since it has access only to them.
24th May 2018, 2:40 AM
Mickel
Mickel - avatar
+ 4
Something to take into account is that the controllers only work within the block that they are established. That means that if in the example I mentioned you try to access one of the properties outside of its <div>, it will not work. This is because that controller only affects what is inside of that tag. This is important for you to define in what element you will use it.
24th May 2018, 2:42 AM
Mickel
Mickel - avatar