Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS controllers: Move common code to separate file

Tags:

angularjs

I have some controllers with some common code, specifically a $scope.$watch that is identical for several controllers. How can I put this code in a separate file and import the common code in the various controllers that needs this $watch?

like image 815
EricC Avatar asked Sep 19 '14 15:09

EricC


1 Answers

You could use a service by passing in your controller's scope:

angular.module('app').service("CommonFunctions", ['SomeService', function(SomeService) {
    var commonFunctions = {};
    commonFunctions.init = function(scope){
        scope.$watch(function(){},function(){})
    };
    return commonFunctions;
}]);

angular.module('app').controller('Ctrl1', 
['$scope','CommonFunctions',function($scope,CommonFunctions) {
    CommonFunctions.init($scope);
}]);

angular.module('app').controller('Ctrl2', 
['$scope','CommonFunctions',function($scope,CommonFunctions) {
    CommonFunctions.init($scope);
}]);

This way you're using the individual controller's scope, but using a common method within a service. You could also use angular.extend($scope, AService) within a controller if you want common functionality from a service actually added to controller scopes.

Here's a working Fiddle: http://jsfiddle.net/rhcjdb7L/

Sure that's very cool and all, but are you sure you don't want to use $rootscope.$broadcast()? This is pretty well written: http://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

like image 183
Brad Wells Avatar answered Sep 23 '22 09:09

Brad Wells