Is there an established convention regarding declaration of controllers? (Or any form of module-level configuration).
I have observed two different approaches in use:
var shoppingCartModule = angular.module('ShoppingCart',[])
shoppingCartModule.controller('CheckoutCtrl', function($scope) { ... });
vs
angular.module('ShoppingCart').controller('CheckoutCtrl', function($scope) { ... });
Are there any benefits between the two approaches? Also, is there a preferred (or emerging) convention?
I'm specifically interested in benefits for non-trivial apps with many modules, where declarations of controllers and modules may span many files.
AngularJS ng-controller Directive The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.
AngularJS Example The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller. The myCtrl function is a JavaScript function. AngularJS will invoke the controller with a $scope object.
The $ in AngularJs is a built-in object.It contains application data and methods.
The controller in AngularJS is a JavaScript function that maintains the application data and behavior using $scope object. You can attach properties and methods to the $scope object inside a controller function, which in turn will add/update the data and attach behaviours to HTML elements.
Personally I do the following (reasons after):
angular.module('myApp', []);
angular.module('myApp').controller('myController', ['$dependency', 'anotherDependency',
function($dependency, anotherDependency) {
...
}
]);
Reasons:
app.something
you don't know what app
is, with `angular.module('myApp').something' it's pretty obvious what that is.Edit: Just remembered a cool video I saw on this very topic a while ago - http://www.egghead.io/video/tTihyXaz4Bo. If you haven't checked out John's site, I highly recommend it. I was so impressed with his videos I donated, and you should too!
Personally, I find it be a little bit cleaner this way:
angular.
module('myApp').
controller('myController', ['$dependency', 'anotherDependency', myAppController]);
function myAppController($dependency, anotherDependency) {
...
}
Or, even more better:
var Controllers = {};
Controllers .someController = function myAppController($dependency, anotherDependency) {
...
}
angular.
module('myApp').
controller('myController', ['$dependency', 'anotherDependency', Controllers .someController]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With