angularjs - 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 没有问题,但我真的需要用表达式来做。这是小提琴,我相信有办法。
解决方案
第一:我不认为 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!'
}
})
推荐阅读
- c# - 如何检测计算机是否安装了新的基于 Chromium 的 Edge 浏览器?
- java - 将 JSP 代码迁移到 Spring Controller 和 Service
- android - 接收来自 Firebase 的消息
- c++ - 带有 lambda 函数的 C++ 回调
- python - 为什么我不能在 python 中运行同一类的方法?
- javascript - 在angular7中对打字稿中的字母数字数组进行排序
- java - 如何在 Quarkus 中禁用安全性
- javascript - React Native - 未找到 SetTimeout 变量
- python - 通过索引将标量值分配给 numpy 数组
- c - 将特定的 8 位分配给 uint8_t