gpt4 book ai didi

angularjs - 如何使用 Controller As 表示法访问父属性

转载 作者:行者123 更新时间:2023-12-03 06:42:15 25 4
gpt4 key购买 nike

我认为 Controller 的使用方式如下:

<body ng-controller="MainCtrl as main">
<div ng-controller="ChildCtrl as child">
{{ main.parentValue }} + {{ child.childValue }}
</div>
</body>

像这样定义我的 Controller :

app.controller('MainCtrl', function($scope) {
this.parentValue = 'Main';
});

app.controller('ChildCtrl', function($scope) {
this.childValue = 'Child';
// I want to access the property of the parent controller here
});

ChildCtrl如何设置MainCtrl的name属性?这里是Plunkr .

使用 $scope 符号,我可以从子 Controller 访问 $scope.parentValue。如何使用 Controller As 表示法实现相同的功能?

最佳答案

由于您使用“controller as”表示法,因此在您的 ChildCtrl 中,您可以使用 $scope.main 访问 MainCtrl,例如$scope.main.name.

请参阅下面的代码片段。

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
this.name = 'Main';
this.test = {};
});

app.controller('ChildCtrl', function($scope) {
this.name = 'Child';
alert($scope.main.name);
});
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-controller="MainCtrl as main">
<div ng-controller="ChildCtrl as child">
{{ main.name }} + {{ child.name }}
</div>
</body>

</html>

关于angularjs - 如何使用 Controller As 表示法访问父属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com