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

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -