Accessing a service from another module in AngularJS

I have this code where I have a service hexafyin one module that I want to access in another 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 model hex2in this example is never solved! What am I doing wrong?

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

This is a 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>
+4
source share
1 answer

AngularJS HTML-. ngApp, , . HTML, angular.bootstrap.

, div myApp2 .

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

, 2

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

. hex2 ​​

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

Source: https://habr.com/ru/post/1649093/


All Articles