-->

Access parent scope variable in child controller t

2019-09-14 21:51发布

问题:

How would I access parent scope variable in child controller template?

I have child controller (time picker) and want to change the button text under child controller by parent controller. How would I modify the value of child template using parent controller?

Plunker code: https://plnkr.co/edit/WVFVTF7wKsGTgOrBfADB?p=previewenter code here

回答1:

Child views have automatically access to $scope properties. Just access them as you normally would.

Modifying parent properties is slightly more "difficult". I would suggest using a setter to modify the property on parent. If you modify it as you normally would (by simply assigning a value), it will create a locally scoped copy with the new value instead of modifying the existing on the parent.

Do the following on your parent controller:

$scope.myValue = "foo";
$scope.changeMyValue = function (value) {
    $scope.myValue = value;
}

Then call the changeMyValue method from your child controller.

If you want to modify child properties, I would suggest events.

Do this in your parent controller to fire an event:

$scope.$broadcast('myEventName', myValue);

You can receive the event on your child controller this way:

$scope.$on('myEventName', (event, value) => handleEvent(value));