javascript - Angular model looses scope with ng-included in directive -
this question has reply here:
angularjs - losing scope when using ng-include 4 answersi wasn't sure on how title question, here goes ..
i'm trying setup dynamic way alter out templates within of directive using ng-include method. i've set 2 plunker examples , although 1 should work other, doesn't seem case.
html 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 2 directives (one main, , 1 nested child):
angular.module('myapp', ['test']); angular.module('test', []) .directive('main', [ function () { homecoming { restrict: 'e', template: '<input type="text" ng-model="mymodel"><br><br><child></child>' }; } ]) .directive('child', [ function () { homecoming { restrict: 'e', template: '<input type="text" ng-model="mymodel">' }; } ]);
easy. when running app both fields populate respectively model changes.
example #2: http://plnkr.co/edit/3ajctyfjelezbqvswwbm?p=preview
the html stays same, js little different:
angular.module('myapp', ['test']); angular.module('test', []) .directive('main', [ function () { homecoming { restrict: 'e', template: '<input type="text" ng-model="mymodel"><br><br><child></child>' }; } ]) .directive('child', [ function () { homecoming { 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 interact first input generated, both inputs update respectively should. here's when gets interesting ... when/if interact sec input (the 1 generated ng-include
) loose binding. forever... if it's created own version of model. afterwards, changing first input has no effect on second.
what happening here? indeed creating new instance of mymodel
? , if so, how can avoided when using ng-include
method?
this no weird, psl said, ng-include creates new scope.
if want create behaviour keeps models attached, should alter
<input type="text" ng-model="mymodel">
to:
<input type="text" ng-model="$parent.mymodel">
javascript angularjs angularjs-directive angularjs-scope angularjs-ng-include
No comments:
Post a Comment