![](/img/trans.png)
[英]How do I pass functions from the service to the controller and call it there Angularjs syntax es6?
[英]How to pass data between two components in angularjs syntax es6?
我想將數據從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>
元素。
有關更多信息,請參見
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.