Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple controllers defined via module does not work

Tags:

angularjs

When defining controllers as global functions, everything works fine. But when using the modules to declare and "assign" the controllers, only the first controller is used to resolve the bindings. What am i missing?

<!doctype html>
<html>
<head/>
<body>
  <div ng-app="flintstones">
    <div ng-controller="flintstoneCtrl">
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <hr>
      <h1>Hello {{yourName}}!</h1>
    </div>
  </div>
  <div ng-app="rumbles">
    <div ng-controller="rumbleCtrl">
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <hr>
      <h1>Hello {{yourName}}!</h1>
    </div>
  </div>
</body>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script>

  var flintstones = angular.module("flintstones", []);
  flintstones.controller("flintstoneCtrl", function flintstoneCtrl($scope) {
    $scope.yourName = "Fred";
  });

  var rumbles = angular.module("rumbles", []);
  rumbles.controller("rumbleCtrl", function rumbleCtrl($scope) {
    $scope.yourName = "Barney";
  });

</script>

</html>
like image 432
Florian Salihovic Avatar asked Apr 18 '13 10:04

Florian Salihovic


2 Answers

@Arun is correct. However, in your case I'm guessing you don't really want to bootstrap Angular twice, but simply use controllers defined in different modules.

This is usually done by having a page/site module which have dependencies on all modules required, in your case flintstones and rumbles.

angular.module('flintstones', []).controller('flintstoneCtrl', ...);
angular.module('rumbles', []).controller('rumbleCtrl', ...);

// Create a module with dependencies.
angular.module('myApp', ['flintstones', 'rumbles'])...

In your html, you then simply use ng-app="myApp" and content from that module and all its dependencies will be accessible.

<html ng-app="myApp">
  <body>
    <div ng-controller="flintstoneCtrl">...</div>
    <div ng-controller="rumbleCtrl">...</div>
  </body>
</html>
like image 166
Martin Avatar answered Oct 20 '22 21:10

Martin


I think, one page can have only one ng-app as default, in your case you have two ng-app definitions.

If you have multiple apps in a page you have to do manual bootstrapping

like image 28
Arun P Johny Avatar answered Oct 20 '22 19:10

Arun P Johny