我有这个代码,我在一个模块中有一个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>
答案 0 :(得分:2)
每个HTML文档只能自动引导一个AngularJS应用程序。在文档中找到的第一个ngApp将用于定义作为应用程序自动引导的根元素。要在HTML文档中运行多个应用程序,必须使用angular.bootstrap手动引导它们。
所以用id定义myApp2 div。
if(empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "off"){
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
enter code hereheader('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
所以你必须手动引导app2,如下所示
<div id="App2" ng-app="myApp2" ng-controller="myCtrl2">
你的代码中还有一个错误。 hex2模型应设置为
angular.bootstrap(document.getElementById("App2"), ['myApp2']);