【问题标题】:Cannot pass object to component in Angular using ng-repeat无法使用 ng-repeat 将对象传递给 Angular 中的组件
【发布时间】:2017-08-03 17:27:08
【问题描述】:

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

<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>

我也想确定块类型返回对应的模板,这里是我的块组件:

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;

这是我的控制器:

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

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

【问题讨论】:

  • 可能与如何在对象中传递控制器有关。控制器本身是否工作不会引发错误?我会认为它会

标签: javascript angularjs angularjs-ng-repeat angular-components


【解决方案1】:

组件绑定不会在组件控制器初始化后立即反映在控制器上下文中。您可以在组件的 $onInit 生命周期钩子中附加绑定。

class ArticleBlockController {
  constructor() {
    'ngInject';
  }
  $onInit(){
    console.log(this.block);
  }
}

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

$compileProvider.preAssignBindingsEnabled(true);

注意:设置preAssignBindingsEnabled 不是您应该在您的 应用。基本上,它已被引入以使 Angular 1 组件看起来与 Angular 2 组件 API 相同。虽然迁移它会让您的工作更轻松。

【讨论】:

  • 是的,你是对的,谢谢,但是如何获取对象属性来确定我应该使用哪个模板?我仍然有这个问题,因为我在 $attrs 中获得了字符串值
猜你喜欢
  • 2016-11-28
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多