In short i have next question:
How correctly pass the controller to the directive and use it in transclude block.
What i want is to give directive user a chance to use some specific controller in transclude block. The purpose to implement some specific actions that not common for different directive usages.
I believe that it is possible to send controller as attribute and then somehow add its fields to the scope in link function, but i don't see correct way.
My current try is next. Base html:
<mylist items="list" ctrl="internalCtrl1">
<li>
{{element}} <a ng-click="showAbc()">ShowAbc</a>
</li>
</mylist>
<h3>List2</h3>
<mylist items="list" ctrl="internalCtrl2">
<li>
{{element}} <a ng-click="showXyz()">ShowXyz</a>
</li>
</mylist>
Directive:
<div>
<p>Cool list</p>
<!--<ul ng-controller="ctrl">-->
<ul>
<ng-transclude></ng-transclude>
</ul>
<div>
directive script:
.........
scope: {
ctrl: "=",
items: '='
},
controller: function($scope){
//some common stuff
},
link: function($scope, $element, $attrs, controller, $transclude) {
$scope.$watch("items", function(items) {
var el = $element.find("ul");
el.empty();
if(items)
items.forEach(function(item) {
var childScope = $scope.$new();
childScope.element = item;
$transclude(childScope, function(content) {
el.append(content);
});
});
});
}
Full code: https://plnkr.co/edit/kPSu9s9xpHJdACFzofdP
Any help very appreciated.
Upd. I have 2 problems now:
- when i use passed controller in directive - i got error 'ctrl' is not a function
- when i use fixed controller in directive - there is no access to control functions from transclude block
ng-controlleron the element that holds this content? e.g.<myList><div ng-controller="insideController">some content that needs insideController</div></mylist>scope,=is two way bound data exchange; you can't pass functions in this way. if you really want to do it this way, you would need&to passctrlas a function. However, it's still not really clear why you would do this, and it feels like you are asking for help with a workaround for a problem you aren't fully explaining, and there may be a better way to solve the problem if you explained it more fully.