【问题标题】:Angular 1.5 component issueAngular 1.5 组件问题
【发布时间】:2017-01-16 07:29:10
【问题描述】:

我决定创建像单独的小部件这样的组件,例如父级将配置传递给它,组件获取数据(父级不需要来自子级的数据)。但是在某些情况下,例如父项中的某些更新,可能会影响显示的数据。所以我想对孩子说:重新获取数据,而配置保持不变。但这不会导致 $onChanges 回调触发,因为指向配置对象的链接是相同的,所以我以一种 hacky 的方式修复了它:

vm.childConfig = _.assign({}, vm.childConfig);

对我来说,这很好用,但很难看。有没有更好的解决方案? (创建 $watch,发出事件似乎是更糟糕的解决方案)

一些示例代码:

<parent-component>
        <child-component config="childConfig"></child-component>
</parent-component>

JS:

function ParentComponentController () {
    vm.childConfig = {show: true, ...}

    vm.onItemDelete = function () {
      vm.childConfig = _.assign({}, vm.childConfig); // I want to call `fetchData` so I force child $onChanges to fire.
    }
}

function ChildComponentController () {
   vm.$onInit = function () {
      fetchData()
   }
   vm.$onChanges = function () {
      // will not fire if will not change the config object reference
      fetchData(changes)
   }
}

所以我想要强制孩子打电话给$onChanges

附:我不喜欢让子组件成为哑组件(父组件将获取的数据传递给它)的想法,当然它会解决这个问题,但数据只需要子组件,它会使父组件更胖。

【问题讨论】:

  • 不太清楚你在问什么。尝试向我们展示一些演示您的问题的代码。

标签: javascript angularjs web-component


【解决方案1】:

你的意思是这样的吗?

JS

angular.module("app")
    .component(
        "ChildComponent",
        {
            controller: ChildComponentCtrl,
            bindings: {
                config: "<",
                update: "<"
            }
        }
    );


function ChildComponent () {
    var init = false;

    function init() {
        // Set up config
        init = true;
    }

    function update() {
        // config remains the same but do something else
    }

    this.$onChanges = function () {
        if (angular.isDefined(this.config) && !init) {
            init();
        }
        else if (angular.isDefined(this.update)) {
            update();
        }
    };
}

标记

<parent-component>
    <child-component config="childConfig" update="update"></child-component>
</parent-component>

编辑 - 为确保更新不止一次,请执行以下操作:

子组件

    this.$onChanges = function () {
        if (angular.isDefined(this.config) && !init) {
            init();
        }
        else if (angular.isDefined(this.update) && update) {
            update();
        }
    };

父组件

function doUpdate() {
    this.update = true;
    // Rest update so that it works next time
    $timeout(function () {
        this.update = false;
    });
}

【讨论】:

  • 这似乎是第一次工作,但如果我需要第二次更新孩子,将 'update' 标志设置为 'true' 将不起作用($onChanges 不会火)。
猜你喜欢
  • 2016-10-03
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 2016-10-25
  • 2016-06-04
  • 1970-01-01
  • 1970-01-01
  • 2016-09-10
相关资源
最近更新 更多