【问题标题】:Update Two Way Bound value $onDestroy in Angular 1.5 Component在 Angular 1.5 组件中更新双向绑定值 $onDestroy
【发布时间】:2017-01-13 19:52:15
【问题描述】:

我正在使用 AngularJS 1.5 创建一系列动态表单组件。

我正在使用 ng-if 来显示和隐藏表单组件。当组件被销毁时,我将它从它的父级数组中删除,但我还想将传入的双向绑定对象的值设置为 null。

以下是我正在使用的代码的简化版本:

app.component('textInput', {
    bindings: {
        model: '='
    },
    require: {
        parent:'^formPanel'
    },
    templateUrl: 'app/shared/form/formFields/textInput/textInputView.html',
    controller: function() {

        var self = this; 

        this.$onInit = function() {
            this.parent.addField(this);
        },
        this.$onDestroy = function() {
            this.model = null;
            console.log(this);
            this.parent.removeField(this);
        }
    }
});

这会将值记录为 null,但在组件范围之外,angular 尚未注册更改,我无法运行摘要周期,因为 $onDestroy 事件已经在进行中。

【问题讨论】:

    标签: javascript angularjs angularjs-components


    【解决方案1】:

    您应该能够使用回调来实现这一点。

    所以在父作用域里有一个类似this的函数(这是回调):

    $scope.setMyModel = function(val){
      $scope.myModel = val;
    };
    

    并在组件HTML文件中将回调传递给组件:

    <test-input
      my-model="myModel"
      my-callback="setMyModel " 
    />
    

    并且this在组件的绑定中收集回调:

    bindings: {
      myModel: '=',
      myCallback: '='
    },
    

    随后调用 $onDestroy 函数中的回调:

    this.$onDestroy = function() {
      this.myCallback(null);
      this.parent.removeField(this);
    }
    

    可能有更好的方法,但这将确保父作用域始终控制设置myModel 持有的值。

    【讨论】:

      猜你喜欢
      • 2016-07-21
      • 2017-06-05
      • 2017-05-10
      • 2016-07-03
      • 2016-09-10
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      相关资源
      最近更新 更多