作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用定义 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.
$scope
的作用正如其名称所示:即它在 $scope
上定义 ViewModel 属性。这最适合与嵌套 Controller 共享范围,这些 Controller 可以使用 $scope
驱动自己的逻辑或更改它。这是一个例子:
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/
我是一名优秀的程序员,十分优秀!