javascript - How does one preserve scope with nested directives? -


my goal create flexible set of directives reusable , lightweight ui elements. each has isolated scope, , many of them transclude content. want each directive black box - user ideally wouldn't need know whether nests directive internally when writing content transcluded.

according angular guide directives:

the transclude option changes way scopes nested. makes contents of transcluded directive have whatever scope outside directive, rather whatever scope on inside. in doing so, gives contents access outside scope.

i have found works described when using single directive. however, if there directive nested in 1 transcludes content, transcluded content resolved within scope of outer directive, rather scope on outside. problem, because prevents users knowing in scope transcluded content resolved!

for example: (fiddle)

.controller('main', function ($scope) {     $scope.value = '"main"';     $scope.expected = $scope.value; })  .directive('outer', function () {     return {         restrict: 'e',         replace: true,         transclude: true,         scope: { expected:'=' },         controller: function ($scope) {             $scope.value = '"outer"';         },         template: '<div><inner expected="expected"><span ng-transclude></span></inner></div>'     }; })  .directive('inner', function () {     return {         restrict: 'e',         replace: true,         transclude: true,         scope: { expected:'=' },         controller: function ($scope) {             $scope.value = '"inner"';         },         template: '<div><span>\'value\' expected resolved in scope {{expected}}, , resolved in scope </span><span ng-transclude></span></div>'     }; }) 

and html:

<div ng-controller="main">     <inner expected="value">         <span>{{value}}</span>     </inner>     <hr/>     <outer expected="value">         <span>{{value}}</span>     </outer> </div> 

inside <inner></inner> element {{value}} evaluated within parent scope "main" (as expected). however, inside <outer></outer> element {{value}} evaluated within isolated scope of outer "outer" (not expected). in way, template of directive can affect scope in transcluded content resolved!

is there way work around issue?

this sucks indeed! angular calls 1 parent in isolated scope, , if doesn't find needs stops looking. solve this, can manually call scope's parent so:

controller: function ($scope) {     $scope.value = $scope.$parent.value || '"outer"'; } 

this "make" him further chain.


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -