I want to share two variables across 2 different controllers, one nested into another:
approach1:
<body ng-controller="WGHomeLanCtrl">
<section><div><a>{{text}}</a></div></section>
<section>...</section>
<section ng-controller="WGHomeSurveyCtrl"> <div> <a>{{lan}} and {{lan2}}</a></div></section>
In my controller file, I have:
var HomeControllers = angular.module('HomeControllers', []);
HomeControllers.controller('WGHomeLanCtrl', function($scope, $http) {
$scope.lan = "en";
$http.get("lan/lan_".concat($scope.lan, ".json")).success(function(data) {
$scope.text = data;
});
HomeControllers.controller('WGHomeSurveyCtrl', ['$scope',
function($scope) {
$scope.lan2= $scope.text;
$scope.lan = $scope.$parent.lan;
}]);
The actual result is that, the {{text}} in the parent controller is showing up, meaning that the $http part is working fine. in the child scope, the {{lan}} is showing correct value too; however the {{lan2}} is not showing correct; the {{lan2}} is shown as plain text.
Any thoughts why?? Thank you!
text
gets updated after the lan2
is assigned the value of text
because of the $http call delay, so lan2
becomes whatever text
is at that point.
The simplest solution would be to just use {{text}}
in your view. However, if it's not an option (if, for example, text
might be used for something else and changed) then you can add a watcher or emit a message and update lan2
whenever the text
is updated.
Btw. all your parent scope's variables should be available inside children scopes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.