I wasn't sure on how to properly title this question, so here it goes ..
I'm trying to setup a dynamic way to change out templates inside of a directive using the ng-include method. I've set up two Plunker examples and although one should work just like the other, that doesn't seem to be the case.
HTML for both Examples:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<main></main>
</body>
</html>
Example #1: http://plnkr.co/edit/bi3Plrm8xufuN79Nvajj?p=preview
I'm setting up two directives (one main, and one nested as a child):
angular.module('myApp', ['Test']);
angular.module('Test', [])
.directive('main', [
function () {
return {
restrict: 'E',
template: '<input type="text" ng-model="myModel"><br><br><child></child>'
};
}
])
.directive('child', [
function () {
return {
restrict: 'E',
template: '<input type="text" ng-model="myModel">'
};
}
]);
Easy. When running the app both fields populate respectively as the model changes.
Example #2: http://plnkr.co/edit/3ajcTyfJElEzbqvsWwBM?p=preview
The HTML stays the same, but the js is a little different:
angular.module('myApp', ['Test']);
angular.module('Test', [])
.directive('main', [
function () {
return {
restrict: 'E',
template: '<input type="text" ng-model="myModel"><br><br><child></child>'
};
}
])
.directive('child', [
function () {
return {
restrict: 'E',
controller: function($scope) {
$scope.myTemplate = 'test-template.html'
},
template: "<div ng-include='myTemplate'></div>"
};
}
]);
test-template.html:
<input type="text" ng-model="myModel">
This time, if I interact with the first input that is generated, both inputs update respectively as they should. Here's when it gets interesting ... When/if I interact with the second input (the one generated by ng-include
) I loose all binding. Forever... Almost as if it's created its own version of the model. Afterwards, changing the first input has no effect on the second.
What is happening here? Is it indeed creating a new instance of myModel
? And if so, how can this be avoided when using this ng-include
method?