ng-include controller scope

I am having a problem in AngularJs when using ng-include to include an html template that has its own controller.

The problem in short is that I am able access scope variables defined in the controller of the included template in the template itself but can't do the opposite (accessing a model defined in the template inside its controller).

This is my index.html page at which I include test.html template:

<html ng-app="myApp">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="app.js"></script>

  <body>
    <div ng-controller="TestController" ng-include="'test.html'"></div>
  </body>
</html>

Here is the test.html template:

<div>
{{foo}}
<br />
<input type="text" ng-model="username" />{{username}}
<br />
<button ng-click="go()">Click here</button>
</div>

And finally this is my controller:

myApp.controller('TestController', function($scope) {
  $scope.foo = 'Hello World';
  $scope.go = function() {
    console.log('Username = ' + $scope.username);
  }
});

With no problem I can do the following:

But I can't do the following

Here is a plunker.

Thanks in advance.

Upvotes: 2

Views: 4497

Answers (2)

Alhuck
Alhuck

Reputation: 1029

Its because ng-include directive creates new scope always when it is included,

instead of declaring your controller in

<div ng-controller="TestController" ng-include="'test.html'"></div>

declare it in test.html itself,

<div ng-controller="TestController">
 {{foo}} <br />
 <input type="text" ng-model="username"/>    {{username}}     <br />
 <button ng-click="go()">Click here</button>
</div>

Hope this helps!

Upvotes: 1

borracciaBlu
borracciaBlu

Reputation: 4225

Ok what i suggest you to do is alias your controller and inser the model in its scope.

Alias your controller:

<div ng-controller="TestController as testCtrl" ng-include="'test.html'"></div>

Actually this code is allowing you to use testCtrl to prefix your variables and isert them in your scope.

Inser the model in the controller scope:
So now you can insert your model in the scope.

<input type="text" ng-model="testCtrl.username" />{{testCtrl.username}}

So now in your controller you can access to that variable like that:

$scope.testCtrl.username

Upvotes: 0

Related Questions