Question

I'm trying to pass a template through a directive to a dynamic controller (known at runtime from the directive perspective).

Something like this:

<my-dir ctrl="PersonCtrl">  
    <h1>{{person.name}} - {{person.age}}</h1>
</my-dir>

var data = {
    name: "Alex",
    age: "24"
};

function PersonCtrl($scope){
    $scope.person = data;        
}

myApp.directive('myDir', function($controller){
    return {
        restrict: "EA",
        scope: {
            ctrl: "@"
        },
        transclude: true,
        controller: function($scope, $element, $attrs) {

        },
        template: "<div>{{ctrl}}</div><div ng-transclude></div>",
        link: function($scope, $element, $attrs) {
            $controller($attrs.foo, {$scope: {}});
        }
    };
});

see jsFiddle

The controller is found and instantiated, but somehow the binding of the transcluded template to it doesn't work. Do I miss some order requirement or is there a way to bind this controllers scope to the transcluded template?

Was it helpful?

Solution

Found it - should have binded the controller to the $$nextSibling scope!

$controller($attrs.ctrl, {$scope: $scope.$$nextSibling});

updated jsFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top