Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从AngularJS中的不同模块访问服务_Angularjs - Fatal编程技术网

从AngularJS中的不同模块访问服务

从AngularJS中的不同模块访问服务,angularjs,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

我有一个代码,其中一个模块中有一个
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>

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

因此,用一个id定义myApp2 div

<div id="App2" ng-app="myApp2" ng-controller="myCtrl2">
你的代码中还有一个错误。hex2模型应设置为

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

我想这是因为你在申报2NG应用
myApp
已包含在
myApp2
中,因此只需将`ng app=“myApp2”`移动到body@austinthedeveloper你在2NG应用上完全正确,我得到了答案!
angular.bootstrap(document.getElementById("App2"), ['myApp2']);
$scope.hex2 = hexafy.myFunc(155); // it was $scope.hex before