Thursday, April 11, 2013

AngularJS controller

So I spent quite a lot of time figuring out how to set up an AngularJS controller without polluting the default namespace/scope. Here is the recipe with a simple click listener showing that it works:

index.html

<doctype html>
<html ng-app="main">
  <head></head>
  <body ng-controller="mainController">
    <button ng-click="log()">Log</button>
    <script type="text/javascript" src="angular.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
  </body>
</html>

main.js

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

main.controller('mainController', function($scope) {
  $scope.log = function() {
    console.log('Logging a simple message...');
  }
});

You can easily see which names map to which implementation, e.g. ng-app="main" is angular.module('main', []);, so on and so fourth.

Note: It is extremely important to invoke angular.module with the second argument (in this case, the empty array), otherwise, it is not going to work.

2 comments:

  1. Thanks for your post. I’ve been thinking about writing a very comparable post over the last couple of weeks, I’ll probably keep it short and sweet and link to this instead if thats cool. Thanks. custom pool builder spicewood tx

    ReplyDelete