I'm new to Angular and currently using version 1.6.
I'm implementing the component style of Angular. I just want to ask what's the best way to communicate from parent to child components? I know there is an existing question but I have a specific scenario (I'm not sure if it's unique or not).
Here is the scenario:
Modal -> create new todo -> Parent ( update the object ) -> personal todo ( update the list )
- I have a modal for creating todo.
- Then after creating new todo pass the value on the parent to update the object of todo.
- And when I updated the parent list of todo pass to the personal todo components to update the list on the view.
angular.module('tab')
.controller('TabController', TabController);
function TabController() {
let vm = this;
let updatedTodoObject = {};
vm.$onInit = function () {
vm.personalTodo = vm.todo.own_todo;
vm.externalTodo = vm.todo.external_todo;
}
vm.$onChanges = function (changes) {
console.log('I'm triggered');
}
vm.updateTodoList = updateTodoList;
function updateTodoList( result ) {
updatedTodoObject = angular.copy(vm.todo);
updatedProjectObject.user_todos.push(result)
if( vm.todo !== updatedTodoObject) {
vm.todo = updatedTodoObject;
} else {
console.log("Still in reference");
}
}
vm.getUpdatedTodotList = function( ) {
return vm.todo;
}
}
angular.module('...')
.component('...', {
bindings: {
onResultTodoUpdated: '&'
},
controllerAs: 'todo',
controller: ['TodoService', '$log', '$state', function(TodoService, $log, $state) {
let vm = this;
let todo = {};
vm.newTodoModal = function() {
TodoService.newTodoModal()
.then(function (TodoName) {
TodoService.createTodo(TodoName)
.then(function(response) {
if( response.status === 201 ) {
todo = {
...
...
}
vm.onResultTodoUpdated( { result: todo } );
}
})
.catch(function(error) {
console.log(error);
});
angular.module('...')
.component('...', {
bindings: {
todos: "<"
},
controllerAs: 'personal',
controller: function(){
let vm = this;
vm.isShowTodoArchived = false;
vm.$onInit = function () {
getWatchedTodo();
}
function getWatchedTodo () {
vm.todos = vm.todos;
vm.todosSize = vm.todos.length;
}
My question again is how I can pass the updated data after I create to the child component which is in charge of displaying the todo list?
UPDATED
<div class="tab-pane active" id="todosTab">
<nv-new-todo on-result-todo-updated="todo.updateTodoList(result)"></nv-new-project>
<div class="my-todos">
<nv-personal-todo todos="todo.personalTodo" ></nv-personal-todo>
<nv-external-todo todos="todo.externalTodo"></nv-external-todo>
</div>
</div>
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…