Firman Firdaus
Firman Firdaus

Reputation: 23

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.

Upvotes: 1

Views: 139

Answers (1)

Joe Enzminger
Joe Enzminger

Reputation: 11190

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();

}]);

Upvotes: 1

Related Questions