Skip to content
This repository has been archived by the owner on Nov 4, 2024. It is now read-only.

Angular Standards

Will Jones edited this page Feb 18, 2015 · 3 revisions

Always annotate dependency injection

myMoudule.controller('MyController', ['$scope', 'someService', function($scope, somesrv){}]);

// OR

var MyController = function($scope, somesrv){};
MyController.$inject = ['$scope', 'somesrv'];
myModule.controller('MyController', MyController);

Services

  • Factory
    • Use to communicate directly with API
  • Service
    • Only use when data needs to be shared across modules, other services, controllers, or directives

Controller

  • Use to prepare or process data.
  • Use as the link between Services and Directives (avoid calling Services from a Directive)

Directive

  • Prefer restricting to attribute and class, rather than element
  • Always use templateUrl, unless the template is two or less pairs of HTML tags
  • Controller may be inline function or reference name to external controller
  • Only perform DOM manipulation in the linking function
myModule.directive('directiveName', [function(){
	return {
    	restrict: 'AC', //Must be at least 'AC', can't just be 'E',
        templateUrl: 'path/to/template.tpl.html',
        controller: function(){ // Or external reference 'MyController'
			/**
			only data preparation and communication to Services here (i.e., the service that connects to the API)
			**/
		},
        link: function(scope, elm, attrs){
        	//Data should already be formatted
        	//Only manipulate the DOM here
        }
    }
}])

Templates

  • Only perform Angular expressions in the template when there is no other choice. Handle data filtering or preparation in the directive link functions or controller.

DON'T

<div ng-repeat="item in items | limitTo: 30"></div>

DO

<div ng-repeat="item in items track by $index"></div>
//--- DO
.controller('Contorller', ['$scope', '$filter', 'service', function($scope, $filter, service){
  this.getItems = function(){
    var items = service.getItems();
    items = $filter('limitTo')(items, 30);
    return items;
  };
}])
.directive('name', [function(){
  return {
   ...
   link: function($scope, elm, attrs, Ctrl){
     scope.items = Ctrl.getItems();
   }
}]);
Clone this wiki locally