AngularJS Controllers | SoloLearn: Learn to code for FREE!


AngularJS Controllers

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

5/23/2018 9:02:22 PM

Paul Grasser 💻

2 Answers

New Answer


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) => { $ = 'Sololearn'; }); app.controller('otherCtrl', ($scope) => { $ = '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.


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.