首页 > 解决方案 > AngularJS 1.5+ 将转换表达式绑定到子组件控制器

问题描述

我必须做一件奇怪的事情,并且为此挣扎了很长时间:如何“冻结”嵌入的表达式以绑定在特定的组件中,而不是绑定到当前控制器的默认行为?所以使用这样的代码:

<parent>
    <child>{{childCtrl.childValue}}</child>
</parent>

我想将表达式绑定到组件的控制器以显示其数据。

组件如下所示:

.component('parent',{
    template: `<p ng-transclude></p>`,
    transclude: true
})

.component('child',{
    template: `
    <li>expression hard coded: <b>{{childCtrl.childValue}}</b>
    <li>expression value from transclusion: <b><span ng-transclude></span></b>`,

    transclude: true,
    controllerAs: 'childCtrl',
    controller: function() {
        this.childValue = 'working!'
    }
})

注入一些被动 HTML 没有问题,但我真的需要用表达式来做。这是小提琴,我相信有办法。

标签: angularjs

解决方案


第一:我不认为 ng-transclude 是要走的路,因为它使用外部控制器范围编译您想要转换的任何内容。

第二:使用Angularjs的思维方式(甚至是组件的思维方式),从组件本身外部访问组件的模型/范围是没有意义的,并且试图这样做破坏了封装原则和单一职责原则上,外部组件不应该告诉内部组件如何处理其模型。所以我想问一下,这真的是你需要做的事情吗?这是最好的设计吗?您对此有具体的实际用例吗?

您可以做的是配置要显示的值,请参阅此 plunker

.component('parent',{
    template: `
    <p ng-transclude></p>`,
    transclude: true
})

.component('child',{
  bindings: {
    displayedAttribute: "@"
  },
    template: `
    <li>expression hard coded: <b>{{childCtrl.childValue}}</b>
    <li>expression with configured value: <b>{{childCtrl[childCtrl.displayedAttribute]}}</b>`,

    transclude: true,
    controllerAs: 'childCtrl',
    controller: function($compile, $scope) {
        this.childValue = 'working!'
        this.anotherChildValue= 'also working!'
    }
})

推荐阅读