Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  125] [ 4]  / answers: 1 / hits: 39034  / 12 Years ago, wed, july 4, 2012, 12:00:00

How do I create some sort of utils bundle that would be accessible from all my controllers?



I have this route code in my main module:



'use strict';

angular.module('lpConnect', []).
config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/home', {template: 'views/home.html', controller: HomeCtrl}).
when('/admin', {template: 'views/admin.html', controller: AdminCtrl}).
when('/connect', {template: 'views/fb_connect.html', controller: MainAppCtrl}).
otherwise({redirectTo: '/connect'});
}]);


I want a function that can be common to HomeCtrl, AdminCtrl and MainAppCtrl.



How should I do it in AngularJS?


More From » angularjs

 Answers
109

The way to define common code in angular is through Services.



You would define a new service like so :



.factory('CommonCode', function ($window) {
var root = {};
root.show = function(msg){
$window.alert(msg);
};
return root;
});


In your controller you would inject this service..like so



function MainAppCtrl($scope,CommonCode)
{
$scope.alerter = CommonCode;
$scope.alerter.show(Hello World);
}


Just include CommonCode as an argument to your controller function.. Angular will take care of injecting it for you ( Read on Dependancy Injection ..to understand what is happening here. )


[#84481] Monday, July 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mickaylag

Total Points: 333
Total Questions: 108
Total Answers: 93

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;