I have an angular application and several modules.
As you can see below, i am calling a directive that in mod2, at the mod1template.html.
myvar gets value in mod1Ctrl
But angular initialize child first and myvar appears empty in mod2's controller.
When i googled it, there are some solutions but anything for my case.
pre post links works for when both parent and child are directives but my mod1 haven't any directive.
I don't want to pass parameter as attribute
Is there any more solutions for my case ?
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);
}
You Could use $broadcast In your case. When $scope.myvar value change,watch will fire broadcast event and it will be listen by its child scope.
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)
});
}