Phelio Gnomi

My words from my mind

Monthly Archives: March 2016

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.