【发布时间】:2019-05-13 23:41:51
【问题描述】:
我想将数据从 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>
【问题讨论】:
-
不要在 HTML 的组件名称中使用大写字母。同样在 HTML5 中,斜线是一个错误,除了 HTML5 之前的 void 元素。错误恢复将导致浏览器忽略它,并将该标签视为常规开始标签。这通常以缺少结束标记而告终,导致后续元素成为子元素而不是兄弟元素。
-
我在
<todo todos="$ctrl.todos" ></todo>上更改了<Todo todos="$ctrl.todos" / >,但它不起作用 -
你用的是哪个版本的angularjs?
标签: javascript angularjs ecmascript-6