我想将数据从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/