gpt4 book ai didi

angularjs - 将绑定(bind)传递到组件中的嵌入范围

转载 作者:行者123 更新时间:2023-12-02 09:12:07 25 4
gpt4 key购买 nike

在 AngularJS 1.5 中,我想将一个绑定(bind)从组件传递到(多槽)嵌入范围 - 作为模板中的引用(在一个特定的或所有模板中 - 没有任何一种方法都可以)。

这是为了创建通用的自定义选择列表

// Component
.component('mySelect', {
bind: {
collection: '<'
},
transclude:{
header: 'mySelectHeader',
item: 'mySelectItem'
},
templateUrl: 'my-select-template',
controller: function(){
.....
}
});

...
// Component template
<script id="my-select-template" type="text/ng-template">
<ol>
<li ng-transclude="header"> </li>
<li ng-transclude="item"
ng-click="$ctrl.select($item)"
ng-repeat"$item in $ctrl.collection">
</li>
</ol>
</script>

...
// Example usage
<my-select collection="[{id: 1, name: "John"}, {id: 2, name: "Erik"}, ... ]>
<my-select-head></my-select-head>

<!-- Reference to $item from ng-repeate="" in component -->
<my-select-item>{{$item.id}}: {{$item.name}}</my-select-item>

</my-select>

这可以通过 .component() 实现吗?使用嵌入的自定义指令?

最佳答案

在你的父组件 my-select 中保留一个像“selectedItem”这样的变量

在您的子组件 my-select-item 中,需要如下所示的父组件

require: {
mySelect: '^mySelect'
}

并在 my-select-item 组件的 Controller 中访问您的父组件

 $onInit = () => {
this.mySelectedItem= this.mySelect.selectedItem; // to use it inside my-select-item component.
};
select($item) {
this.mySelect.selectedItem = $item; // to change the selectedItem value stored in parent component
}

现在可以从以下位置访问所选项目

<my-select-item>{{selectedItem.id}}: {{selectedItem.name}}</my-select-item>

关于angularjs - 将绑定(bind)传递到组件中的嵌入范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39574792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com