gpt4 book ai didi

javascript - 无法使用 ng-repeat 将对象传递到 Angular 中的组件

转载 作者:行者123 更新时间:2023-12-03 04:48:25 24 4
gpt4 key购买 nike

我正在使用基于 Angular 1.6 组件的方法构建应用程序。我有一个包含“ block ”组件的“文章”组件,我想在 ng-repeat 循环中将数据从文章传递到 block ,但无法实现此目的:这是我的文章模板:

<md-content class="article-detail">
<div layout="row">
<div flex="20"></div>
<div layout="column" flex="60" layout-align="center center">
<div class="article-preview">
<div class="article-photo">
<img ng-src="{{$ctrl.article.image}}"/>
</div>
<h1 class="article-info">ARTICLE</h1>
</div>
<div class="article-content">
<h1>{{$ctrl.article.title.toUpperCase()}}</h1>
</div>
<article-block ng-repeat="block in $ctrl.article.blocks" block="block"></article-block>
</div>
</div>
</div>
<div flex="20">
</div>
</div>
</md-content>

我还想确定 block 类型以返回相应的模板,这是我的 block 组件:

import controller from './block.controller'
import venueBlock from './venue-block.html';
import imageBlock from './image-block.html';
import titleBlock from './title-block.html';
import contentBlock from './content-block.html';

let views = {venueBlock, imageBlock, titleBlock, contentBlock};

let articleBlockComponent = {
bindings: {
block: '<'
},
controller,
template: function ($attrs) {// $attrs.block === 'block' it is a string, but not an object
'ngInject';
return views[$attrs.block.type + "Block"];
}
};
export default articleBlockComponent;

这是我的 Controller :

class ArticleBlockController {
constructor() {
'ngInject';
console.log(this.block);//undefined
}
}
export default ArticleBlockController;

我花了很多时间试图找出错误,但还是没有发现。我是 Angular 的新手,非常感谢您的帮助

最佳答案

组件 Controller 初始化后,组件绑定(bind)不会立即反射(reflect)在 Controller 上下文中。您可以在组件的 $onInit 生命周期 Hook 中附加绑定(bind)。

class ArticleBlockController {
constructor() {
'ngInject';
}
$onInit(){
console.log(this.block);
}
}
<小时/>

如果您希望以这种方式工作您的组件,那么您必须调整 $compileProvider 中的一些设置,其中您必须启用 preAssignBindingsEnabled

$compileProvider.preAssignBindingsEnabled(true);

Note: Setting preAssignBindingsEnabled isn't preferred way that you should be doing in your application. Basically it has been introduced to make Angular 1 component to looks same as that of Angular 2 component API. While migrating it will make your job much easier.

关于javascript - 无法使用 ng-repeat 将对象传递到 Angular 中的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768004/

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