2017-10-13 6 views
1

のは、私は次のようにコンポーネントを持っているとしましょう:コンポーネントコントローラに値を読む

.component('book', { 
    bindings: { 
     type: '=?' 
    },... 
}); 

だから、親コントローラに私がようvm.type = null;としてtypeを宣言し、このコンポーネントを呼び出すためにしました:<book type="vm.type" />

ここでの値をコンポーネントコントローラのtrueに設定すると、値はtrueになります。

だから私が欲しいのは唯一の他の言葉で、コンポーネントコントローラの内部で設定することができ、親コントローラ内vm.typeの値にアクセスするだけです:vm.typeは親コントローラ内部の読み取り専用変数であるが、それは変更することができますコンポーネントコントローラ。

片方向バインディングは、コンポーネントコントローラで変更した場合、親コントローラのvm.typeの値が変更されないため、明らかに機能しません。

どうすれば解決できますか?

+0

、右? –

+0

@CommercialSuicide nope、親コントローラ内のコンポーネントコントローラ変数を読みたい。この変数はコンポーネントコントローラ内でのみ変更でき、親コントローラでは変更できない –

答えて

0

あなたは親コントローラに子変数を読みたい場合は、次の操作を行うことができ、$emit$broadcastを使用して、親と子のコントローラ間で通信することができます:

$scope.yourVariable = 'Data to send'; 
$scope.$emit('yourCustomEventName', $scope.yourVariable); // will emit event with data to parent controller 

child.controller 親。コントローラ

// $scope.$on will catch your custom event 
$scope.$on('yourCustomEventName', function (event, data) { 
    console.log(data); // will print "Data to send", received from child controller 
}); 
0

親コンポーネントからモデルを「読み込み専用」にする場合は、親コンポーネントを介してモデルを変更しないでください。コンポーネントアーキテクチャは木のようなものなので、親は子よりも高いです。

あなたのケースでは、子コンポーネントのモデルを更新してから、バインドイベントを介して親コンポーネントに更新された値を渡すだけで済みます。

も注意here's a working fiddle demonstrating the following code次のコード、:

子コンポーネント:

.component('child', { 
    bindings: { 
    onValueChange: '&' 
    }, 
    controller: function() { 
    this.total = 0; 
    this.increaseTotal =() => { 
     this.total++; 
     this.onValueChange({ 
     value: this.total 
     }); // Here you updated the parent model 
    }; 
    }, 
    template: `<button ng-click="$ctrl.increaseTotal()">Increase total</button>` 
}) 

親コンポーネント:あなたは、子コントローラ内部の親の変数を読みたい

.component('parent', { 
    controller: function() { 
    this.setValue = (val) => { 
     this.childValue = val; 
    }; 
    }, 
    template: `Total in Parent Component: {{$ctrl.childValue}} 
        <child on-value-change="$ctrl.setValue(value)"></child>` 
}) 
関連する問題