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
?
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/
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