如何在同一个html页面中使用2个angularjs应用程序?
以下是重现的代码,其中第二个应用程序失败:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<div ng-app="myApp1" ng-controller="myCtrl1">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
var app1 = angular.module("myApp1", []);
app1.controller("myCtrl1", function($scope) {
$scope.firstName = "John1";
$scope.lastName = "Doe1";
});
</script>
</body>
</html>
此外,我尝试使用angular.bootstrap
但没有运气,如建议的here
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<div ng-app="myApp1" ng-controller="myCtrl1">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
angular.bootstrap(document, ['myApp']);
var app1 = angular.module("myApp1", []);
app1.controller("myCtrl1", function($scope) {
$scope.firstName = "John1";
$scope.lastName = "Doe1";
});
angular.bootstrap(document, ['myApp1']);
</script>
</body>
</html>
更新
工作示例:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div id="firstApp" ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>
<div id="firstApp1" ng-app="myApp1" ng-controller="myCtrl1">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
let appEl1 = document.getElementById("firstApp");
angular.bootstrap(appEl1, ['myApp']);
var app1 = angular.module("myApp1", []);
app1.controller("myCtrl1", function($scope) {
$scope.firstName = "John1";
$scope.lastName = "Doe1";
});
let appEl2 = document.getElementById("firstApp1");
angular.bootstrap(appEl2, ['myApp1']);
</script>
</body>
</html>
答案 0 :(得分:1)
问题是你在document
引导了两个应用程序。它需要位于angular.bootstrap documentation here
div
)上
例如:
<div id="firstApp">
let appEl1 = document.getElementById("firstApp");
angular.bootstrap(appEl1, ['myFirstApp']);
答案 1 :(得分:0)
您需要使用
angular.bootstrap(document.getElementById("appID"), ['myApp1']);
带
<div id="appID" ng-app="myApp1" ng-controller="myCtrl1">
这将手动启动它。
(您在注册控制器的第一种情况下也有一个拼写错误(?):app.controller("myCtrl1"
应为app1.controller("myCtrl1"
)