javascript - Angular Directive inside another Directive stops updating when inner directive is edited -


so have directive inside directive. both directives use same property shared using service , both have input edit property. outer directive uses "transclude" display inner directive. when editing outer directive, inner directive updates correctly. but, when updating inner directive, connection seems lost.

here code:

var myapp = angular.module('myapp',[]); myapp.controller('myctrl', function($scope, dataservice) { });  myapp.directive('dir1', function(dataservice){   return {     restrict: 'e',     transclude:true,     template: '<h3>directive 1</h3><input type="text" ng-model="item"/><div ng-transclude></div>',     link: function(scope, elem, attr) {       scope.data = dataservice;     }   }; });  myapp.directive('dir2', function(dataservice){   return {     restrict: 'e',     template: '<h3>directive 2</h3><input type="text" ng-model="item"/>',     link: function(scope, elem, attr) {       scope.data = dataservice;     }   }; });  myapp.factory('dataservice', [function(){   return { item: "" }; }]); 

and it's view:

<div ng-controller="myctrl">   <dir1>     <dir2>      </dir2>   </dir1> </div> 

i made jsfiddle show problem http://jsfiddle.net/stevescerri/19l24ul6/2/

any appreciated cannot find work around yet, thanks! :)

by default directives create new, prototypically inherited scopes. prototypical inheritance means (in short) when reading property not exist in scope, angular tries read parent. when writing property always written in scope. dir2 creates scope within scope of dir1. when dir2 reads ng-model property, reads scope of dir1. when writes it, written own scope. dir1 knows nothing inner scope, directives display different value type in "directive 2" textbox.

moreover using ng-model="item" not reference value of dataservice, intended. merely references item property of current scope. using `ng-model="data.item" solve current problem.


having said above, better idea (imo) use angular's support custom input controlls - defining own "extension" of ng-model described here under "custom control example". code become like:

<dir1 ng-model="data.item" /> <dir2 ng-model="data.item" /> 

this makes directives less coupled actual expression editing, @ expense of work. while you're @ it, go isolated scopes too, directives become components, independent of context. data.item not editable in directive, use isolated scope's = binding.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -