如何将transcluded模板绑定到不同的控制器?

时间:2013-10-22 22:12:40

标签: angularjs angularjs-directive angularjs-scope angularjs-controller transclusion

我正在尝试通过指令将模板传递给动态控制器(从指令角度看运行时)。

这样的事情:

<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

找到并实例化控制器,但以某种方式将已转换模板绑定到它不起作用。我是否会错过某些订单要求,或者是否有办法将此控制器范围绑定到已转换的模板?

1 个答案:

答案 0 :(得分:0)

找到它 - 应该将控制器绑定到$$ nextSibling范围!

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

updated jsFiddle