zpy*_*dee 378 angularjs angularjs-scope
我已经设置了我的控制器 data-ng-controller="xyzController as vm"
我有一个父/子嵌套控制器的场景.通过使用$parent.vm.property我在嵌套的html中访问父属性没有问题,但我无法弄清楚如何从我的子控制器中访问父属性.
我试过注入$ scope然后使用$scope.$parent.vm.property,但这不起作用?
有人可以提供建议吗?
Die*_*erg 615
如果您的HTML如下所示,您可以执行以下操作:
<div ng-controller="ParentCtrl">
<div ng-controller="ChildCtrl">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
然后,您可以按如下方式访问父作用域
function ParentCtrl($scope) {
$scope.cities = ["NY", "Amsterdam", "Barcelona"];
}
function ChildCtrl($scope) {
$scope.parentcities = $scope.$parent.cities;
}
Run Code Online (Sandbox Code Playgroud)
如果要从视图中访问父控制器,则必须执行以下操作:
<div ng-controller="xyzController as vm">
{{$parent.property}}
</div>
Run Code Online (Sandbox Code Playgroud)
见jsFiddle:http://jsfiddle.net/2r728/
更新
实际上,因为您cities在父控制器中定义了子控制器将继承所有范围变量.所以理论上你不必打电话$parent.上面的例子也可以写成如下:
function ParentCtrl($scope) {
$scope.cities = ["NY","Amsterdam","Barcelona"];
}
function ChildCtrl($scope) {
$scope.parentCities = $scope.cities;
}
Run Code Online (Sandbox Code Playgroud)
AngularJS文档使用这种方法,在这里你可以阅读更多关于$scope.
另一个更新
我认为这是原始海报的更好答案.
HTML
<div ng-app ng-controller="ParentCtrl as pc">
<div ng-controller="ChildCtrl as cc">
<pre>{{cc.parentCities | json}}</pre>
<pre>{{pc.cities | json}}</pre>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
JS
function ParentCtrl() {
var vm = this;
vm.cities = ["NY", "Amsterdam", "Barcelona"];
}
function ChildCtrl() {
var vm = this;
ParentCtrl.apply(vm, arguments); // Inherit parent control
vm.parentCities = vm.cities;
}
Run Code Online (Sandbox Code Playgroud)
如果使用该controller as方法,还可以按如下方式访问父作用域
function ChildCtrl($scope) {
var vm = this;
vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"
}
Run Code Online (Sandbox Code Playgroud)
如您所见,访问有许多不同的方法$scopes.
function ParentCtrl() {
var vm = this;
vm.cities = ["NY", "Amsterdam", "Barcelona"];
}
function ChildCtrl($scope) {
var vm = this;
ParentCtrl.apply(vm, arguments);
vm.parentCitiesByScope = $scope.pc.cities;
vm.parentCities = vm.cities;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<div ng-app ng-controller="ParentCtrl as pc">
<div ng-controller="ChildCtrl as cc">
<pre>{{cc.parentCities | json}}</pre>
<pre>{{cc.parentCitiesByScope | json }}</pre>
<pre>{{pc.cities | json}}</pre>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
Ste*_*rov 46
我刚检查过
$scope.$parent.someProperty
Run Code Online (Sandbox Code Playgroud)
适合我.
它会
{{$parent.someProperty}}
Run Code Online (Sandbox Code Playgroud)
为了观点.
当您使用as语法时,例如 ParentController as parentCtrl,定义控制器然后访问子控制器中的父作用域变量使用以下内容:
var id = $scope.parentCtrl.id;
Run Code Online (Sandbox Code Playgroud)
parentCtrl父控制器的名称在何处使用as语法,并且id是在同一控制器中定义的变量.
| 归档时间: |
|
| 查看次数: |
477350 次 |
| 最近记录: |