Phelio Gnomi

My words from my mind

Sharing objects between Modules in AngularJs

It turns out that sharing objects between angular modules is as simple as injecting a module into another module. Say myApp has some controllers and providers or other objects and myApp2 want to use some of those controllers. When creating myApp2, inject myApp into it and myApp2 now has access to all the objects in myApp to the extend that the HTML can use the controller from myApp without any extra codes.

// Common library of some sort
app = angular.module("myApp", []);

app.value('someVal', 'This is a val');

app.controller("controller1", ['$scope','someVal', function($scope, someVal){
$scope.someVal = someVal;
}]);

// My actual module
app2 = angular.module("myApp2", ["myApp"]);

app2.controller("searchController", ['$scope', function($scope){
// ... some controller's codes
}]);
<body ng-app='myApp2'>
<div ng-controller='controller1'>
{{someVal}}
</div>
</body>

Note that the HTML is using ‘controller1’ which is from ‘myApp’. I’ve built an app in AngularJs and going to create another one using the similar format. It also means that most of the codes are going to be shared. I’m glad that I don’t have to do much refactoring.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: