Access $scope of Component within Transclusion in AngularJS 1.5

有些话、适合烂在心里 提交于 2019-12-12 02:17:30

问题


How can I make the $scope of a component accessable within transclusion area of that component? here an example:

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

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

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


        }
    }
})

回答1:


You may use $parent to access isolated component scope, e.g.:

<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;
        }
    }
})

Or else you may define dedicated transclusion slot:

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

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


来源:https://stackoverflow.com/questions/42580610/access-scope-of-component-within-transclusion-in-angularjs-1-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!