简体   繁体   中英

Why don't I get the same output 3 times in the attached code?

I am currently trying to understand some features in AngularJS. I wrote a codePen of my attempt ( http://codepen.io/ssj666/pen/XbgKXX ).

My code:

<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML>
   <HEAD>
   <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>   
   </HEAD>
<BODY>
  <div ng-app="test" ng-controller="testCtrl"> 
    <ul>
    <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
    </li>
    </ul>
</div>
<div ng-app="t" ng-controller="testCtrl"> 
  <ul>
    <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
    </li>
  </ul>
</div>
<div ng-app="t2" ng-controller="tCtrl"> 
  <ul>
    <li ng-repeat="x in names">
    {{ x.Name + ', ' + x.Country }}
    </li>
  </ul>
</div>

   <script>
   var app = angular.module('test', []);
     app.controller('testCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function (response) {$scope.names = response.records;});
    });
  </script>
   <script>
   var app = angular.module('t', []);
   app.controller('testCtrl', function($scope, $http) {
    $http.get("http://www.w3schools.com/angular/customers.php")
    .success(function (response) {$scope.names = response.records;});
  });
  </script>
  <script>
  var app = angular.module('t2', []);
  app.controller('tCtrl', function($scope, $http) {
  $http.get("http://www.w3schools.com/angular/customers.php")
  .success(function (response) {$scope.names = response.records;});
  });
  </script>

  </BODY>
</HTML>

I hope there isn't a typo crashing everything, but if so I dont see it. Is it possible for a single angularJS controller to control tags with different ng-app-names? Why is it not possible for a second controller to do the same om scope attributes of a different tag (with a different ng-app-name)?

I am currently investigating if my question is a possible duplicate.

Instead of using different apps, you will want to use one app with different controllers. See it like a project, you use 1 project with different classes, or 1 project with different html templates or whatever you can think of. The app is the parent, the controllers are its children. The controllers need to have unique names though!

You can't have many ng-app unless you bootstrap it manually. Angular will take the first ng-app to bootstrap everything. That's why you don't see anything on the other two divs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM