joshualan
joshualan

Reputation: 2140

Accessing a service from a different module in AngularJS

I have this code where I have a hexafy service in one module that I want to access in a different module:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">

<p>The hexadecimal value of 255 is:</p>

<h1>{{hex}}</h1>

</div>

<div ng-app="myApp2" ng-controller="myCtrl2">

<p>The hexadecimal value of 155 is:</p>

<h1>{{hex2}}</h1>

</div>

<p>A custom service whith a method that converts a given number into a hexadecimal number.</p>

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc(255);
});

var app2 = angular.module('myApp2', ['myApp']);
app2.controller('myCtrl2', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc(155);
});

</script>

</body>
</html>

However, the hex2 model in this example never gets resolved! What am I doing wrong?

I found my solution! As per the comments below, you can really only have 1 angular app per page but as many controllers as you want.

This is the working solution!

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp">

<div ng-controller="myCtrl">

<p>The hexadecimal value of 255 is:</p>

<h1>{{hex}}</h1>

</div>

<div ng-controller="myCtrl2">

<p>The hexadecimal value of 155 is:</p>

<h1>{{hex2}}</h1>

</div>

<p>A custom service whith a method that converts a given number into a hexadecimal number.</p>

<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});
app.controller('myCtrl', function($scope, hexafy) {
  $scope.hex = hexafy.myFunc(255);
});

app.controller('myCtrl2', function($scope, hexafy) {
  $scope.hex2 = hexafy.myFunc(155);
});

</script>

</body>
</html>

Upvotes: 4

Views: 311

Answers (1)

Sasank Sunkavalli
Sasank Sunkavalli

Reputation: 3964

Only one AngularJS application can be auto-bootstrapped per HTML document. The first ngApp found in the document will be used to define the root element to auto-bootstrap as an application. To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap instead.

So define the myApp2 div with an id .

<div id="App2" ng-app="myApp2" ng-controller="myCtrl2">

So u have to manually bootstrap the app2 as below

angular.bootstrap(document.getElementById("App2"), ['myApp2']);

One more mistake in ur code . The hex2 model should be set as

$scope.hex2 = hexafy.myFunc(155); // it was $scope.hex before

Upvotes: 2

Related Questions