【问题标题】:AngularJS 1.5+ Bind a trancluded expression to child component controllerAngularJS 1.5+ 将转换表达式绑定到子组件控制器
【发布时间】:2019-01-11 01:08:07
【问题描述】:

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

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

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

组件如下所示:

.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 没有问题,但我也确实需要使用表达式来做到这一点。 Here's the fiddle,我相信有办法的。

【问题讨论】:

    标签: angularjs


    【解决方案1】:

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

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

    您可以做的是配置要显示的值,see this 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!'
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2017-04-04
      • 2017-06-17
      • 2023-03-21
      • 2016-12-12
      • 2018-12-10
      • 2016-12-24
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      相关资源
      最近更新 更多