简体   繁体   中英

AngularJs: How to communicate between two scopes

I try to follow an example from http://blog.novanet.no/creating-multilingual-support-using-angularjs/ to make multilingual support using AngularJS. This example works well.

I try another way to implement that. I use ng-include to manage module separation of the header, content and footer by using the AngularJS ng-include .

My HTML structure is like this:

<div ng-include = "'header.html'"> </ div>
<div ng-include = "'content.php'"> </ div>
<div ng-include = "'footer.html'"> </ div>

I save my work on Plunker

My question is, when I try to implement multi-language, and put the selector of language in header.html and the result on content.php it is not working.

When your templates create models, they do so on the current scope, which isn't shared with your controller scope (as mentioned in a previous answer, ng-include creates a new child scope). Because of the way inheritance works, items added to this child scope are not visible to the parent (or siblings).

However, If you add items to an item already on the parent scope (google "dot notation angular"), those additions will be visible to the parent and siblings.

A good way to do this is use the controller-as syntax. I've updated your Plunk

<body ng-app="myApp" ng-controller="myController as vm">

    app.controller('myController',['$scope', 'translationService', 
function ($scope, translationService){  

  //Run translation if selected language changes
  $scope.translate = function(){
       translationService.getTranslation($scope, $scope.vm.selectedLanguage);
   };

   //Init
   $scope.vm.selectedLanguage = 'en';
   $scope.translate();

}]);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM