I have joined Anti-IF Campaign

Angularjs Best Practices : create controller

How to create secure and safe controller in Angularjs :

// Use strict mode globally to secure the code and speed up the execution
"use strict";

// Use anonymous function to not pollute the global scope
(function() {

// Declare new module
angular.module('mymod', []);

// Declare new controller with a standard javascript function
// to encourage IDE completion and simplify javascript code understanding
var myCtrl = function($scope, $http) {
 $scope.text = 'hello world';

// Explicitly define the dependencies required for controller to be insensitive to the minification
myCtrl.$inject = ['$scope', '$http'];

// Recover a module using its name without pollute the global context of unnecessary variables
angular.module('mymod').controller('myctrl', myCtrl);


See that in action : jsfiddle

2 commentaires:

  1. Hi, good points, but I would add 3 more:

    * give every anonymous function a name to simplify debugging when bad things happen
    * use my utility script https://github.com/bahmutov/stop-angular-overrides to catch name clashes.
    * use array syntax for injecting dependencies `m.controller(['$scope', function ctrl($scope) { ... }]);`

    And one more - since you are inside a closure, I would declared the module at the end and use chaining to attach everything it provides

    angular.module('mymod', [])
    .controller('myctrl, myCtrl);