我是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>

最佳答案

因为您在执行myapp时将覆盖第一个var new= angular.module('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()有所不同

10-06 00:15