gpt4 book ai didi

angularjs - 使用 Controller As 方法访问继承范围

转载 作者:行者123 更新时间:2023-12-02 20:08:14 25 4
gpt4 key购买 nike

使用定义 Controller 的原始方法,访问父级作用域相当简单,因为子级作用域通常继承自其父级作用域。

app.controller("parentCtrl", function($scope){
$scope.name = "Parent";
})
.controller("childCtrl", function($scope){
$scope.childName = "child of " + $scope.name;
});

<div ng-controller="parentCtrl">
{{name}}
<div ng-controller="childCtrl">
{{childName}}
</div>
</div>

Controller 作为方法似乎是 recommended声明 Controller 的方法。但对于 Controller-As,上述方法不再有效。

当然,我可以从 View 中使用 pc.name 访问父作用域:

<div ng-controller="parentCtrl as pc">
{{pc.name}}
<div ng-controller="childCtrl as cc">
{{cc.childName}}
</div>
</div>

我确实对此有一些问题(可能会出现意大利面条式代码),但这个问题是关于从子 Controller 访问父作用域。

我能看到这个工作的唯一方法是:

app.controller("parentCtrl", function(){
this.name = "parent";
})
.controller("childCtrl", function($scope){
$scope.pc.name = "child of " + $scope.name;
// or
$scope.$parent.pc.name = "child of " + $scope.name;

// there's no $scope.name
// and no $scope.$parent.name
});

所以现在,子 Controller 需要了解“pc” - 除了,这应该(在我看来)仅限于 View 。我认为子 Controller 不应该知道 View 决定声明 ng-controller="parentCtrl as pc" 的事实。

问:那么正确的方法是什么?

编辑:

澄清:我不想继承父 Controller 。我希望继承/更改共享范围。因此,如果我要修改第一个示例,我应该能够执行以下操作:

app.controller("parentCtrl", function($scope){
$scope.someObj = {prop: "not set"};
})
.controller("childCtrl", function($scope){
$scope.someObj.prop = "changed";
});

最佳答案

经过研究,我得到以下认识:

Controller-As approach is NOT a substitute for using $scope. Both have their place, and can/should be used together judiciously.

  1. $scope 的作用正如其名称所示:即它在 $scope 上定义 ViewModel 属性。这最适合与嵌套 Controller 共享范围,这些 Controller 可以使用 $scope 驱动自己的逻辑或更改它。
  2. Controler-As 将整个 Controller 对象定义为具有命名范围的 ViewModel(通过 Controller 的别名)。如果 View 决定是否要引用特定 Controller ViewModel,则此方法仅在 View (而非其他 Controller )中效果最佳。

这是一个例子:

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

// Then the controllers could choose whether they want to modify the inherited scope or not:
app.controller("ParentCtrl", function($scope) {
this.prop1 = {
v: "prop1 from ParentCtrl"
};
$scope.prop1 = {
v: "defined on the scope by ParentCtrl"
};
})
.controller("Child1Ctrl", function($scope) {})
.controller("Child2Ctrl", function($scope) {
// here, I don't know about the "pc" alias
this.myProp = $scope.prop1.v + ", and changed by Child2Ctrl";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>

<body ng-app="myApp">
<div ng-controller="ParentCtrl as pc">
<div ng-controller="Child1Ctrl">
<div>I know about the "pc" alias: {{pc.prop1.v}}</div>
</div>
<div ng-controller="Child2Ctrl as ch2">
<div>I only care about my own ViewModel: {{ch2.myProp}}</div>
</div>
</div>

关于angularjs - 使用 Controller As 方法访问继承范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26647460/

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