我有 3 个 div 元素和 3 个 Controller 。
第二个 Controller 可以访问第一个 Controller 。但第三个不起作用。
var app = angular.module("app", [])
.controller("countryController", function () {
this.Name = "Turkey";
})
.controller("cityController", function () {
this.Name = "Istanbul";
})
.controller("streetController", function () {
this.Name = "Istiklal";
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="countryController as countryCtrl">
{{countryCtrl.Name}}
<div ng-controller="cityController as cityCtrl">
{{countryCtrl.Name}} - {{cityCtrl.Name}}
</div>
<div ng-controller="streetController as streetCtrl">
{{countryCtrl.Name}} - {{cityCtrl.Name}} {{streetCtrl.Name}}
</div>
</div>
最佳答案
您无法获取 {{cityCtrl.Name}}
,因为它是第三个 Controller 的同级 Controller 。相反,您可以使用 $parent
或 $rootScope
来获取该值。
或者将其嵌套在第二个 Controller 中:
var app = angular.module("app", [])
.controller("countryController", function() {
this.Name = "Turkey";
})
.controller("cityController", function() {
this.Name = "Istanbul";
})
.controller("streetController", function() {
this.Name = "Istiklal";
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="countryController as countryCtrl">
{{countryCtrl.Name}}
<div ng-controller="cityController as cityCtrl">
{{countryCtrl.Name}} - {{cityCtrl.Name}}
<div ng-controller="streetController as streetCtrl">
{{countryCtrl.Name}} - {{cityCtrl.Name}} {{streetCtrl.Name}}
</div>
</div><!--cityCtrl closed-->
</div>
关于javascript - angularJS 中的嵌套 Controller - 无法从第三个 Controller 访问第二个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653187/