在AngularJS 1.5中访问Transclusion中的$ scope范围

时间:2017-03-03 13:47:34

标签: angularjs components

如何在该组件的转换区域内使组件的$范围可访问?这里有一个例子:

<test>
   {{myVar}}
</test>    

.component('test', {
    transclude:true,
    template:'<ng-transclude></ng-transclude>',
    controller:function($scope){

        this.$onInit = function() {
                        $scope.myVar = 1123


        }
    }
})

1 个答案:

答案 0 :(得分:2)

您可以使用$parent访问隔离的组件范围,例如:

<test>
    {{ $parent.$ctrl.myVar }}
</test>

.component('test', {
    transclude: true,
    template: '<ng-transclude></ng-transclude>',
    controller: function($scope) {
        var ctrl = this;

        this.$onInit = function() {
           ctrl.myVar = 1123;
        }
    }
})

否则您可以定义专用的翻译时段:

<test>
    <some-fancy-slot>
        {{ $parent.$ctrl.myVar }}
    </some-fancy-slot>
</test>

.component('test', {
    transclude: {
        slot: 'someFancySlot'
    },
    template: '<div ng-transclude='slot'></div>',
    controller: ...
})