从AngularJS中的其他模块访问服务

我有这个代码,我在一个模块中有一个hexafy服务,我想在另一个模块中访问:

<!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>

但是,此示例中的hex2模型永远不会得到解决!我究竟做错了什么?

我找到了解决办法!根据下面的评论,你实际上每页只有1个角应用程序,但你可以拥有多个控制器.

这是有效的解决方案!

<!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>

最佳答案 每个HTML文档只能自动引导一个AngularJS应用程序.在文档中找到的第一个ngApp将用于定义作为应用程序自动引导的根元素.要在HTML文档中运行多个应用程序,必须使用angular.bootstrap手动引导它们.

因此,使用id定义myApp2 div.

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

所以你必须手动引导app2,如下所示

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

你的代码还有一个错误. hex2模型应设置为

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