2

我有一個角度應用程序和幾個模塊。
正如你可以看到下面,我打電話mod2,在mod1template.html指令。
myvar在mod1Ctrl中獲取值
但是角度初始化孩子第一個和myvar在mod2的控制器中顯示爲空。
當我GOOGLE了它,有一些解決方案,但任何事情爲我的情況。
預先鏈接適用於父母和孩子都是指令的情況,但我的mod1沒有任何指令。
我不想傳參數作爲屬性角度等待父控制器

有沒有更多的解決方案,我的情況?

mod1template.html: 
<div> 
<mod2-dir></mod2-dir> 
</div> 


angular.module("angApp.mod1", ["ngRoute"]) 
    .config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) { 
     $routeProvider.when("/:myvar1/:myvar2\\_:id", { 
      templateUrl: "Angular/mod1template.html", 
      controller: "mod1Ctrl" 
     }); 

    }]) 
    .controller("mod1Ctrl", ["$routeParams", "$scope", "mod1DataService", function ($routeParams, $scope, mod1DataService) { 
     $scope.myvar = mod1DataService.myvar; 
     } 


angular.module("angApp.mod2", ["ngRoute"]) 
    .directive("mod2Dir", function() { 
     return { 
      restrict: "E", 
      templateUrl: "Angular/mod2template.html", 
      controller: "mod2Ctrl" 
     }; 
    }) 
    .controller("mod2Ctrl", ["$scope", function ($scope) { 
     alert($scope.myvar.Id); 
     } 
+0

您可以使用$ broadcast或$ emit根據ob控制器如何放置。 –

+1

非常感謝,$廣播爲我工作。如果你發佈它作爲答案,我可以接受 –

+0

我加了答案 –

回答

1

你可以使用$廣播你的情況。當$ scope.myvar值更改時,watch將觸發廣播事件,並將按其子範圍進行偵聽。

angular.module("angApp.mod1", ["ngRoute"]) 
    .config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) { 
     $routeProvider.when("/:myvar1/:myvar2\\_:id", { 
      templateUrl: "Angular/mod1template.html", 
      controller: "mod1Ctrl" 
     }); 

    }]) 
    .controller("mod1Ctrl", ["$routeParams", "$scope", "mod1DataService", function ($routeParams, $scope, mod1DataService) { 
     $scope.myvar = mod1DataService.myvar; 
     //asuming that service call is ajax that's why placing watch on on myvar 
     $scope.$watch('myvar', function(newVal, oldVal){ 
      if(newVal != oldVal) 
      $scope.$broadcast('parentControllerLoaded',newVal); //no need to use broadcast event using $rootScope 
     },true); 
    } 



angular.module("angApp.mod2", ["ngRoute"]) 
    .directive("mod2Dir", function() { 
    return { 
     restrict: "E", 
     templateUrl: "Angular/mod2template.html", 
     controller: "mod2Ctrl" 
    }; 
}) 
.controller("mod2Ctrl", ["$scope", function ($scope) { 
    $scope.$on('parentControllerLoaded',function(event, data){ 
     alert(data.id); 
     //you can directly access parent scope from here. 
     //alert($scope.$parent.myvar.Id) 
    }); 
} 
0

嘗試mod2Ctrl使用$超時:

,而不是

alert($scope.myvar.Id); 

使用本

$timeout(function(){ 
    alert($scope.myvar.Id); 
},1); 
+0

謝謝,但我不認爲$超時是最好的方法。當我用1超時延遲嘗試時,它不工作,比我嘗試使用500工作。延遲的變化取決於很多事情。 –