我想将数据从todos组件传递到todo组件,并以列表的形式显示所有元素。
我从服务下载数据并将其放在todos.controller中。在todos.component中,我使用bindings: {todos: '<'}。在todos.html视图中,它以todos = $ ctrl.todos形式提供数据。在todo.html中,对todos进行迭代并想返回todo.name。效果:仅返回'Todo'

todo.service.js

export class TodoService {
  constructor($http) {
  'ngInject';
   this.$http = $http;
 }
  getTodos() {
    return this.$http.get('/api/todos');
  }
}


todos.controller.js

class TodosController {
   constructor(TodoService) {
    'ngInject'
    this.TodoService = TodoService;
   }

    $onInit() {
      this.todos = null;
      this.TodoService.getTodos().then(response =>
        {
           this.todos = response.data;
           console.log(this.todos);
        });

    }
}

export default TodosController;


todo.component.js

import template from './todo.html';
import controller from './todo.controller';
import './todo.scss';

let todoComponent = {
  bindings: {
    todos: '<'
  },
  template,
  controller
};`

export default todoComponent;


todos.html

<h1>Todos</h1>
<ul>
    <todo todos="$ctrl.todos"></todo>
</ul>


todo.html

<div>
    <p ng-repeat='todo in $ctrl.todos track by $index'>Todo:
     {{$ctrl.todo.name}}
    </p>
</div>

最佳答案

更改todo.html,如下所示:

<div>
    <p ng-repeat='todo in $ctrl.todos'>Todo:
     ̶{̶{̶$̶c̶t̶r̶l̶.̶t̶o̶d̶o̶.̶n̶a̶m̶e̶}̶}̶
     {{todo.name}}
    </p>
</div>


同样使用todos.html

<h1>Todos</h1>
̶<̶u̶l̶>̶
    <todo todos="$ctrl.todos"></todo>
̶<̶/̶u̶l̶>̶


<ul>元素的唯一允许内容是零个或多个<li>元素。

有关更多信息,请参见


MDN HTML Reference - <ul> element

关于javascript - 如何使用angularjs语法es6在两个组件之间传递数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56121166/

10-12 00:14