gpt4 book ai didi

angularjs - 如何从更新的父级列表中更新子组件

转载 作者:行者123 更新时间:2023-12-01 08:50:52 25 4
gpt4 key购买 nike

我是 Angular 的新手,目前使用的是 1.6 版。

我正在实现 Angular 的组件样式。我只想问从父组件到子组件的最佳通信方式是什么?我知道存在一个现有问题,但我有一个特定的场景(我不确定它是否独特)。

这是场景:

模态 -> 创建新待办事项 -> 父项(更新对象) -> 个人待办事项(更新列表)

  • 我有一个创建待办事项的模式。
  • 然后在创建新的 todo 后将值传递给父级以更新 todo 的对象。
  • 当我更新了 todo 的父列表时,将传递给个人 todo 组件以更新 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;
    }

    我的问题是如何在创建后将更新的数据传递给负责显示待办事项列表的子组件?

    更新
    <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>

    最佳答案

    如何使用父组件的更改更新子组件
    使用one-way bindings <

    • < or <attr - set up a one-way (one-directional) binding between a local scope property and an expression passed via the attribute attr. The expression is evaluated in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. You can also make the binding optional by adding ?: <? or <?attr.

    For example, given <my-component my-attr="parentModel"> and directive definition of scope: { localModel:'<myAttr' }, then the isolated scope property localModel will reflect the value of parentModel on the parent scope. Any changes to parentModel will be reflected in localModel, but changes in localModel will not reflect in parentModel.

    AngularJS Comprehensive Directive API Reference - scope


    $onChanges生命周期钩子(Hook):
    • $onChanges(changesObj) - Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component.

    AngularJS Developer Guide - Components



    有对象 内容 — 使用 $doCheck生命周期钩子(Hook)
    绑定(bind)对象或数组时 引用 , $onChanges Hook 仅在 时执行值(value) 的引用变化。检查 的更改内容 对象或数组,使用 $doCheck生命周期钩子(Hook):
    app.component('nvPersonalTodo', {
    bindings: {
    todos: "<"
    },
    controller: function(){
    var vm = this;
    this.$doCheck = function () {
    var oldTodos;
    if (!angular.equals(oldTodos, vm.todos)) {
    oldTodos = angular.copy(vm.todos);
    console.log("new content");
    //more code here
    };
    }
    })
    从文档:

    The controller can provide the following methods that act as life-cycle hooks:

    • $doCheck() - Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; implementing this has no effect on when $onChanges is called. For example, this hook could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not be detected by Angular's change detector and thus not trigger $onChanges. This hook is invoked with no arguments; if detecting changes, you must store the previous value(s) for comparison to the current values.

    AngularJS Comprehensive Directive API Reference -- Life-cycle hooks


    了解更多信息,
  • AngularJS angular.equals API Reference
  • AngularJs 1.5 - Component does not support Watchers, what is the work around?

  • 简单的演示

    angular.module("app",[])
    .component("parentComponent", {
    template: `
    <fieldset>
    Inside parent component<br>
    parentData={{$ctrl.parentData}}
    <child-component in-data="$ctrl.parentData"></child-component>
    </fieldset>
    `,
    controller: function () {
    this.$onInit = () => {
    this.parentData = 'test'
    };
    },
    })
    .component("childComponent",{
    bindings: {
    inData: '<',
    },
    template: `
    <fieldset>Inside child component<br>
    inData={{$ctrl.inData}}
    </fieldset>
    `,
    })
    <script src="//unpkg.com/angular/angular.js"></script>
    <body ng-app="app">
    <parent-component>
    </parent-component>
    <body>

    有关详细信息,请参阅
  • AngularJS Developer Guide - Component-based application architecture
  • AngularJS Comprehensive API Reference - scope
  • 关于angularjs - 如何从更新的父级列表中更新子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43297962/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com