【问题标题】:Access $scope of Component within Transclusion in AngularJS 1.5在 AngularJS 1.5 中的 Transclusion 中访问组件的 $scope
【发布时间】:2017-07-23 15:58:39
【问题描述】:

如何使组件的 $scope 在该组件的嵌入区域内可访问?这里是一个例子:

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

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

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


        }
    }
})

【问题讨论】:

    标签: angularjs components


    【解决方案1】:

    您可以使用$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: ...
    })
    

    【讨论】:

      猜你喜欢
      • 2017-05-31
      • 2016-12-15
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      相关资源
      最近更新 更多