javascript - AngularJS : ng-controller on directive does not work on transcluded elements within directive -


here script:

angular.module('myapp',[]) .directive('mysalutation',function(){     return {         restrict:'e',         scope:true,         replace:true,         transclude:true,         template:'<div>hello<div ng-transclude></div></div>',         link:function($scope,$element,$attrs){         }     }; }) .controller('salutationcontroller',['$scope',function($scope){     $scope.target = "stackoverflow"; }]) 

and html:

<body ng-app="myapp">     <my-salutation ng-controller="salutationcontroller">         <strong>{{target}}</strong>             </my-salutation> </body> 

the problem , when salutationcontroller applied on my-salutation directive, $scope.target is not visible transcluded element.but if put ng-controller on <body> or on <strong> element, works. docs says, ng-controller creates new scope.

  • who can explain, how scope , scope of directive interfering each other in case?

  • how can put controller on directive? hints appreciated.

1) problem ng-transclude's scope sibling scope of directive. when put ng-controller parent element, scope created ng-controller parent scope of both directive , ng-transclude. due scope inheritance, transcluded element able bind {{target}} correctly.

2) using custom transclusion bind scope yourself

.directive('mysalutation',function(){     return {         restrict:'e',         scope:true,         replace:true,         transclude:true,         template:'<div>hello<div class="transclude"></div></div>',         compile: function (element, attr, linker) {             return function (scope, element, attr) {                 linker(scope, function(clone){                        element.find(".transclude").append(clone); // add dom                 });              };         }     }; }) 

demo

or using transclude function in link function:

.directive('mysalutation',function(){     return {         restrict:'e',         scope:true,         replace:true,         transclude:true,         template:'<div>hello<div class="transclude"></div></div>',         link: function (scope, element, attr,controller, linker) {            linker(scope, function(clone){                   element.find(".transclude").append(clone); // add dom            });         }     }; }) 

demo


Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -