2017-04-27 69 views
0

我有3個div元素和3個控制器。angularJS中的嵌套控制器 - 無法訪問第三個控制器的第二個控制器

第二個控制器可以訪問第一個控制器。但第三個不起作用。

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>

+1

'$ parent' ....會幫助你。 – Jai

+0

什麼不起作用? –

回答

0

你不能得到{{cityCtrl.Name}},因爲它是第三個控制器的兄弟姐妹。相反,您可以使用$parent$rootScope來獲取該值。第二位指示內

或嵌套它:

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>

0

您不能訪問這樣說: streetCtrlcityCtrl一個孩子。

這不是在控制器之間共享數據的最佳方式,您應該使用service

這是一個dummy Fiddle顯示它如何工作。

相關問題