简体   繁体   English

AngularJS指令中的两种方式数据绑定不起作用

[英]AngularJS two way data binding in directive not working

I have a directive that updates a bound property, but it never seems to update the original property! 我有一个更新绑定属性的指令,但它似乎从未更新原始属性!

directives.directive('recordVideo', [function () {
    return {
        scope: {
            showRecordVideo: '='
        },
        controller: "recordVideoController as ctrl",
        templateUrl: '/views/recordvideo.html'
    };
}]);

<record-video data-show-record-video="showAddScheduleDialog"></record-video>

When I set $scope.showAddScheduleDialog = true in the parent controller, the directive sees the change and shows the dialog. 当我在父控制器中设置$scope.showAddScheduleDialog = true时,指令将看到更改并显示对话框。 When the dialog itself sets its property $scope.showRecordVideo = false the bound property on the parent controller showAddScheduleDialog never updates! 当对话框本身设置其属性$scope.showRecordVideo = false时,父控制器showAddScheduleDialog上的绑定属性将永远不会更新!

Why is this? 为什么是这样?

I have tried putting $scope.$watch on both the parent controller and the directive. 我尝试将$scope.$watch放在父控制器和指令上。 The changes only propogate down to the directive and never back up to the controller! 更改只会传播到指令,而不会备份到控制器!

The problem is caused by javascript prototype inheritance ( the long answer ). 该问题是由javascript原型继承引起的( 很长的答案 )。 The usual hack is to change a property inside: 通常的方法是更改​​内部的属性:

This stays the same: 这保持不变:

scope: {
    showRecordVideo: '='
},

In controller: 在控制器中:

$scope.showRecordVideo = {
    state: true
};

In modal: 在模式中:

$scope.showRecordVideo.state = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM