Access parent scope variable in child controller template - Angular

假装没事ソ 提交于 2019-12-13 08:33:05

问题


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));


来源:https://stackoverflow.com/questions/42258540/access-parent-scope-variable-in-child-controller-template-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!