Business logic for views

AngularJS - What is a Controller?

  • A controller is a set of JavaScript functions bound to a scope

  • Angular will instantiate a new Controller object, using the specified Controller's constructor function

  • The ng-controller directive tells Angular to instantiate the new controller object, and inject the new scope as a dependency

  • Controller contain business logic for the view

  • Used to set initial state of $scope object and add behaviour to the $scope object 

AngularJS - Creating a Controller

Steps for creating controller:

  • Load angularJS library 
  • AngularJS will initialize when the DOM content is loaded,
  • Load Module's (e.g. 'foodcatApp')
  • Add controller code to Module
  • Controller object will be initiated using controller constructor function
  • Constructor scope is also injected in constructor function
  • After initial state of $scope object is set and behaviour is added
  • It will looks for the ng-app and ng-controller directive
  • Start replacing all binding elements (e.g. curly braces, ng-bind).


AngularJS - What is $scope?

  • $scope is an object that refers to the app model

  • $scope provides the execution context for expressions

  • $scope is the glue between the controller and the view

  • $scope can watch expressions and propogate events

  • Attach properties / functions to scope to make them available to the view

  • Any objects or primitives that is added to the $scope are considered model properties

  • $scope are arranged in hierarchical structure


AngularJS - “Controller as” syntax

  • Defines a named scope

  • Defines properties on the function ( Controller ) and not the $scope

  • $scope is still useful for things like $watch ( watching to see if a property changes ) 

AngularJS - Multiple Controllers


AngularJS - Sharing Data across Controllers