DRYing up your controllers
When defining the model data and methods in controllers, you will quickly become tired of typing $scope
repeatedly. Some developers simply take this on the chin and accept it as a necessity of the framework, but there is a superb method that avoids this verbosity and simultaneously makes your controllers more DRY.
Getting ready
Suppose that you have a controller in a fantasy football application, appearing as follows:
app.module('myApp', []) .controller('Ctrl' function($scope) { $scope.team = { name: 'Bears', city: 'Chicago' }; $scope.player = { name: 'Jake Hsu', team: 'Bears', number: 29, position:'RB' }; $scope.trade = function(player1, player2) { // $scope.trade() logic }; $scope.drop = function(player) { // $scope.drop() logic }; });
How to do it…
Even with two scope objects and two methods, the number of times $scope
needs to be typed here...