我有一个有角度的应用程序和几个模块 正如你在下面看到的那样,我在mod2中调用一个指令,在mod1template.html myvar在mod1Ctrl中获取值 但是角度初始化了孩子,而myvar在mod2的控制器中显示为空 当我用谷歌搜索它时,有一些解决方案,但我的情况 前期链接适用于父母和子女都是指令,但我的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 :(得分:2)
你可以使用$ broadcast在你的情况下。当$ 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)
});
}
答案 1 :(得分:0)
尝试在mod2Ctrl中使用$ timeout:
而不是
alert($scope.myvar.Id);
使用此
$timeout(function(){
alert($scope.myvar.Id);
},1);