【问题标题】:How to bind a transcluded template to a different controller?如何将嵌入的模板绑定到不同的控制器?
【发布时间】:2013-10-31 23:59:56
【问题描述】:

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

类似这样的:

<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

找到并实例化了控制器,但不知何故将嵌入的模板绑定到它不起作用。我错过了一些订单要求还是有办法将此控制器范围绑定到嵌入模板?

【问题讨论】:

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


    【解决方案1】:

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

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

    updated jsFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-28
      • 1970-01-01
      • 2020-06-15
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      相关资源
      最近更新 更多