Search code examples
javascriptangularjsangularjs-controllerangularjs-controlleras

why is this controller instantiated only once?


I have the following (also in Plunker):

<!doctype html>
<html 
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
  </head>
  <body ng-app="theApp">
    <div ng-conroller="ExampleCtrl as ctl">
      <input type="text" ng-model="ctl.value"/><br>
      {{ctl.value}}
    </div>
    <div ng-controller="ExampleCtrl as ctl">
      <input type="text" ng-model="ctl.value"/><br>
      {{ctl.value}}
    </div>
    <script>
     angular.module('theApp', [])
            .controller('ExampleCtrl', [
              function () {
                var self = this;
                self.value = 'Lorem ipsum';
                console.log('controller instantiated');
              }
            ]);
    </script>
  </body>
</html>

Looking at the console, I see only one message controller instantiated and only the second inbox has the bound value printed below it:

enter image description here

I was expecting two separate controllers to be instantiated and indeed after filling-in values it appears that there's two independent scopes, however I cannot explain the initial state.


Solution

  • Typo in first ng-controller directive declaration.

    <div ng-conroller="ExampleCtrl as ctl">
    

    should be

    <div ng-controller="ExampleCtrl as ctl">
    

    Working Plunkr