Controllers

a controller is defined with a controller contructor function.

var mod = angular.module('app', []);

mod.controller('MainCtrl', function(){
  // ...
});

it will contain the view-model (vm), whose properties and functions will be availible to the template.

attach to DOM with ng-controller="name".

use controllers to:

  • set up initial state of $scope
  • add behavior to $scope

do not use controllers to:

  • manipulate DOM ( ctrls only contain business logic )
  • format input
  • filter output
  • manage life-cycle of other components ( ex: to create service instances )


say you have the following HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>AngularJS Controllers</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script>
    <script type="text/javascript" src="app.js"></script>
  </head>
  <body>
    <div ng-app="app">
      <h1>Controllers</h1>
      <div ng-controller="MainCtrl">
        <p></p>
      </div>
    </div>
  </body>
</html>

Adding properties to $scope

angular.module('app', []);

angular.module('app').controller('MainCtrl', function($scope){
  $scope.message = 'hello there from scope msg!';
});

Adding behavior to $scope

angular.module('app', []);

angular.module('app').controller('MainCtrl', function($scope){
  $scope.message = 'hello there from scope msg!';

  $scope.updateMessage = function(message){
    $scope.message = message;
  }
});


instead of using $scope, we can instread use the “controller as” syntax where you remove the $scope param in the controller constuctor and instead reference `self.xxx’. you also have to change the controller delaration in the html to the following

html:

<div ng-controller="MainCtrl as main">
  <form ng-submit="main.updateMessage(main.newMessage)">
    <input type="text" ng-model="main.newMessage">
    <button type="submit">Update Msg</button>
  </form>
</div>

js:

angular.module('app').controller('MainCtrl', function (){
  var self = this;

  self.message = 'hello';

  self.changeMessage = function(message){
    self.message = message;
  };
});

we can access parent controllers directly using $parent.