1

I have a pretty strange problem. For some reason, my ng-model only bounds when I nest the same controller twice. Here is my code:

index page:

bbmean_app.controller('mainController', function($scope, $location, mainFactory){
    $scope.test='hello';
    $scope.currentUser = {};


$scope.login = function(){
    console.log($scope.name)

}
<body>
     <div ng-controller='mainController'>
        <div ng-view =""></div>
    </div>
</body>

view page:

<form>
   {{test}}
    <p>Your name:<input type = 'text' ng-model='name' ></p>
    <button type = 'submit' ng-click ='login()'>Login</button>
</form>

so all my views should have a mainController as the controller and it shows 'hello' on the view page meaning it can display test(which implies connection to the controller) but when i click my submit button, the console log is undefined. it only works if my controller is recalled like this:

<div ng-controller = 'mainController'>
    <form>
    {{test}}
    <p>Your name:<input type = 'text' ng-model='name' ></p>
    <button type = 'submit' ng-click ='login()'>Login</button>
    </form>
</div>

I have ng-app around my html and correct head tags in my codes as well. Any ideas?

Minh Nguyen
  • 140
  • 7
  • This has to with scope prototypical inheritance (`ng-view` creates a child scope) and the need to always use a dot `.` in the binding, e.g. `ng-model="obj.name"` - in other words, always bind to a property of an object, not just property of scope. For more info: http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs/14049482#14049482 – New Dev Aug 16 '15 at 02:53

1 Answers1

0

I think this is how you fix that,

      .when('/', {
        templateUrl: 'js/views/index.html',
        replace: true,
        controller: 'mainController',
      })

by declaring the controller in your route, you can access $scope.name with:

      $scope.login = function() {
        var name = $scope.name;
        console.log(name);
      };

without bootstrapping/nesting the mainController in the view.

SuperVeetz
  • 2,128
  • 3
  • 24
  • 37