我是 AngularJS 的新手,我对这段代码有疑问。我想在单个 ng-app
中添加多个 Controller 。但它执行第一个。为什么不是第二个?
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angul /1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-controller="cont1">
<input type="text" ng-model="fullname">
{{fullname}}
</div>
<div ng-controller="cont2">
<input type="text" ng-model="fname">
{{fname}}
</div>
<script>
var app = angular.module("myapp", []);
app.controller('cont1', function ($scope) {
$scope.fullname = "";
});
var new = angular.module('myapp', []);
new.controller('cont2', function ($scope) {
$scope.fname = "";
});
</script>
</body>
</html>
最佳答案
因为当您执行 var new= angular.module('myapp',[]);
时,您将覆盖第一个 myapp
模块。
您的代码应该是:
var app = angular.module("myapp", []);
app.controller('cont1', function($scope) {
$scope.fullname = "";
});
app.controller('cont2', function($scope) {
$scope.fname = "";
});
或
var app = angular.module("myapp", []);
app.controller('cont1', function($scope) {
$scope.fullname = "";
});
angular.module("myapp").controller('cont2', function($scope) {
$scope.fname = "";
});
传递给 module()
的第二个参数[]
造成了差异
关于javascript - 如何在 AngularJS 的单个页面中添加多个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35078579/