This repository has been archived by the owner on Nov 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Angular Standards
Will Jones edited this page Feb 18, 2015
·
3 revisions
myMoudule.controller('MyController', ['$scope', 'someService', function($scope, somesrv){}]);
// OR
var MyController = function($scope, somesrv){};
MyController.$inject = ['$scope', 'somesrv'];
myModule.controller('MyController', MyController);
- Factory
- Use to communicate directly with API
- Service
- Only use when data needs to be shared across modules, other services, controllers, or directives
- Use to prepare or process data.
- Use as the link between Services and Directives (avoid calling Services from a 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 thelinking
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
}
}
}])
- 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();
return $filter('limitTo')(items, 30);
};
}])
.directive('name', [function(){
return {
...
link: function($scope, elm, attrs, Ctrl){
scope.items = Ctrl.getItems();
}
}]);