简体   繁体   English

AngularJs:如何在两个示波器之间进行通信

[英]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. 我尝试遵循http://blog.novanet.no/creating-multilingual-support-using-angularjs/中的示例,以使用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 . 我使用ng-include通过AngularJS ng-include管理标题,内容和页脚的模块分离。

My HTML structure is like this: 我的HTML结构是这样的:

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

I save my work on Plunker 我将工作保存在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. 我的问题是,当我尝试实现多语言时,将语言选择器放在header.html ,结果放在content.php它不起作用。

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). 当您的模板创建模型时,它们会在当前范围内执行此操作,而当前范围不会与您的控制器范围共享(如上一个答案所述,ng-include创建一个新的子范围)。 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. 一个很好的方法是使用controller-as语法。 I've updated your Plunk 我已经更新了您的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();

}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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