为什么Angular 1.5双向绑定在将作用域变量传递给组件绑定时失败

Why does Angular 1.5 two way binding fail when passing a scope variable to component binding?

本文关键字:绑定 组件 失败 定时 变量 Angular 5双 为什么 作用域      更新时间:2024-01-01

因此,我们正在将Angular 1.3范围汤应用程序提高到1.5标准。但我们注意到了一些奇怪的行为。当我们将$scope变量传递到组件绑定中时,它似乎无法正确反映组件内对$scope可变项所做的任何更改。

我们基于$scope的控制器:

app.controller('ParentCtrl', function ($scope) {
      $scope.dates = [...array of dates...]
      $scope.focusDate = new Date()
})

我们的组件标签:

   <section-dates dates="dates" focus-date="focusDate"></section-dates>

组件本身:

app.component("sectionDates", {
bindings: {
    dates: "=",
    focusDate: "="
},
controller: function () {
    this.onClickADate = function (date)
    {
        this.focusDate=date
    }
...
}

单击新日期时,focusDate会在组件中发生更改,但不会在父控制器的$scope中发生更改。为什么会这样?

我们正在经历类似的事情。

我们花了一些时间思考的一个重要概念是,所有组件都具有隔离的$scope。因此,从理论上讲,这可以防止您提到的"$scope汤"问题,但在实践中,这导致需要显式地将数据传入和传出组件,这可能需要一些时间来适应

通常,您希望保持数据不可变,也就是说,防止子组件直接更改数据(在某些特定情况下,双向数据绑定可以改进UI)。

这里的想法是使用单向数据绑定将数据传递到组件中,如下所示:

...    
bindings: { 
    oneWayBindingInput: '<'
}, 
...

然后将事件传回到子组件,然后由父组件处理:

...    
bindings: { 
    oneWayBindingInput: '<'
    onEventOutput: '&'
}, 
...

所以在你的情况下,你可以尝试这样的东西:

组件标签(在父模板中):

<section-dates dates="dates" on-update="handleUpdateEvent($event)"></section-dates>

组件:

app.component("sectionDates", {
bindings: {
    dates: "<",
    onUpdate: "&"
},
controller: function () {
    this.onClickADate = function (date)
    {
        this.onUpdate({$event: {date: date});
    }
...
}

父控制器:

app.controller('ParentCtrl', function ($scope) {
    $scope.dates = [...array of dates...];
    $scope.handleUpdateEvent = function(event) {
        $scope.date = event.date;
    };
})

只是一个简短的提示。如果单向数据绑定到组件中的数据是一个对象,那么它的属性仍然是可变的。单向数据绑定在这里不会被破坏,这是典型的javascript行为。Todd Motto讨论了一种通过克隆数据来打破绑定的伟大技术:

$onChanges() = function(changes) { 
    if(changes.user) { 
        this.user = angular.copy(this.user);
    }
};

有关更多示例,请参阅这些具有有用组件模式的参考:https://toddmotto.com/exploring-the-angular-1-5-component-method/http://dfsq.info/site/read/angular-components-communication