[英]It is possible to keep variable as reference between views when using ng-view?
I have this situation : I have a webpage with two tabs. 我有这种情况:我有一个带有两个标签的网页。 Those tabs need to use ng-view from angularjs. 这些标签需要使用angularjs的ng-view。 The particularity about those tabs is they need to use the same variable in reference, like referencing a variable in c# (ref keyword). 这些选项卡的特殊之处在于它们需要在引用中使用相同的变量,例如在c#中引用变量(ref关键字)。
You can check the Using object section of this demo to know what I mean: http://plnkr.co/edit/zZfUQN?p=preview 您可以检查此演示的“ 使用对象”部分以了解我的意思: http : //plnkr.co/edit/zZfUQN?p=preview
<h3>Using object:</h3>
<div class="example">
<img class="mainImg" ng-src="{{mainImg.url}}" />
<p>This is the parent scope with the main image.</p>
<p>$scope.mainImg.url == {{mainImg.url}}</p>
<div class="thumbs">
<p>Thumbs generated with ng-repeat, with ng-click setting <strong>$scope.mainImg.url</strong> (click on them to see what happens):</p>
<div class="thumbDiv" ng-repeat="img in images">
<img class="thumb" ng-src="{{img}}" ng-click="mainImg.url = img" />
<p>This is a child scope generated by ng-repeat.</p>
<p>$scope.mainImg.url == {{mainImg.url}}</p>
</div>
</div>
</div>
So, the main page is the main container and the tabs are the childs. 因此,主页是主容器,选项卡是子容器。 How keep a variable as reference between those childs for using the same value between childs. 如何在这些子项之间保留变量作为引用,以便在子项之间使用相同的值。
-- EDIT -编辑
I forget to mention something very important : The reference variable can be modified by a child and need the value need to be kept between others childs. 我忘了提到一些非常重要的事情:引用变量可以由孩子修改,并且需要将值保留在其他孩子之间。 Thank for your help, 谢谢您帮忙,
Karine 卡林纳
I think what you're after is $rootScope
. 我认为您需要的是$rootScope
。 Scopes also inherit, so if you define something in a parent scope and you don't override it in the child scope, you can access it. 范围也继承,因此,如果您在父范围中定义某些内容,但未在子范围中覆盖它,则可以对其进行访问。
function MainController($scope, $rootScope) {
$rootScope.sharedVar = 'Hello';
}
function Child1Controller($scope, $rootScope) {
//access $rootScope.sharedVar;
}
function Child2Controller($scope, $rootScope) {
//access $rootScope.sharedVar;
}
EDIT as Anthony Chu mentioned, you could also create a service and inject it into any controllers that need the shared value. 编辑安东尼楚提到的,你也可以创建一个服务,它注入到需要共享价值的任何控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.