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:
- Accessing foo that is defined in the controller in the template
- Accessing username that is defined in the template in the template itself
But I can't do the following
- Accessing username that is defined in the template in the controller (the output is undefined in the go() function)
Here is a plunker.
Thanks in advance.