-2

this simple angular controller:

var WorldCtrl = function ($scope) {
  $scope.population = 7000;
  $scope.countries = [{name: 'India', population: 121}, {name: 'China', population: 178} ];
};

And this controller gets used in this way inside the views

<body ng-app>
<ul ng-controller="WorldCtrl">
  <li ng-repeat="country in countries">
    {{country.name}} has population of {{country.population}}
  </li>
  <hr>
  World's population: {{population}} millions
</ul>
</body>

Question

  1. Is WorldCtrl is a plan-old javascript function object OR there is more to it?
  2. Nowhere in the code, there is line which invokes WorldCtrl() function. how does that happen?
  3. $scope appear to be parameter/argument passed onto WorldCtrl() but it doesn't behave that way. Because it was a normal argument, we could have called it WorldCtrl(foo) and it would still work the same. But $scope seems sensitive to naming & only works when WorldCtrl($scope) is defined. Anyone explain this why?
  4. $scope seems like an object that angular creates on its own & is passed-by reference as WorldCtrl function doesn't return anything useful. so any changes to $scope change the original object which angular then passes into the views. correct?
CuriousMind
  • 33,537
  • 28
  • 98
  • 137

1 Answers1

2

As the commenters suggested, you should read through the documentation and work through the Angular tutorial.

To begin learning, i also heavily recommend egghead.io

Angular works as a backbone for your application. Therefore it adds some conventions which should be adhered to.

WorldCtrl, for example, works as a controller.

Angular uses dependency injection, which is responsible for getting $scope to work. $scope is not a "regular" argument. Injecting it means that you are telling your controller function that you wish to use the $scope object within it.


Think of your application in a new way. You want to show the world population data. Therefore you are in the need of a view which does that job. The view is your HTML markup. Every view should be bound to its own controller. The controller contains the views logic and provides data to it. E.g you could do the following:

  • Define a view which shall show world population data
  • Define a controller for your view, which provides data through the $scope object.
  • Get the data from wherever you want and store it in a service
  • Inject the service to your controller and copy its information to your controller.
Wottensprels
  • 3,307
  • 2
  • 29
  • 38