问题描述
在我rootscope我有控制一个div的可见性的可见
属性
app.run(函数($ rootScope){
$ rootScope.visible = FALSE;
});
示例HTML:
<节NG控制器='oneCtrl'>
<按钮NG点击='切换()'>拨动< /按钮>
< DIV NG秀='看得见'>
<按钮NG点击='切换()'>&安培;倍;< /按钮>
< / DIV>
< /节>
控制器:
VAR oneCtrl =功能($范围){
$ scope.toggle =功能(){
$ scope.visible = $ scope.visible!;
};
}
以上部分工作正常,元素显示或隐藏没有问题。现在,在不同节在同一页我试图改变可见
变量显示格,但它不能正常工作。
<节NG控制器='otherCtrl'>
<按钮NG点击='showDiv()'>显示< /按钮>
< /节>
控制器:
VAR otherCtrl =功能($范围){
$ scope.showDiv =功能(){
$ scope.visible = TRUE;
};
}
在AngularJS, $范围
取值中典型从其父范围了继承,一路 $ rootScope
。在JavaScript中,原始类型的覆盖的当孩子改变他们。所以,当你设置 $ scope.visible
在你的控制器之一,在 $ rootScope
是从未接触过的财产,但而新的可见
属性添加到当前的范围。
在AngularJS,对范围模型值应该总是有一个点,这意味着,而不是原语对象。
不过,您也可以通过注入 $ rootScope
解决您的情况:
VAR otherCtrl =功能($范围,$ rootScope){
$ scope.showDiv =功能(){
$ rootScope.visible =真;
};
}
In my rootscope I have a visible
property which controls the visibility of a div
app.run(function ($rootScope) {
$rootScope.visible = false;
});
Example HTML:
<section ng-controller='oneCtrl'>
<button ng-click='toggle()'>toggle</button>
<div ng-show='visible'>
<button ng-click='toggle()'>×</button>
</div>
</section>
Controller:
var oneCtrl = function($scope){
$scope.toggle = function () {
$scope.visible = !$scope.visible;
};
}
The above section works fine, the element is shown or hide without problems. Now in the same page in a different section I try to change the visible
variable to show the div but it doesn't work.
<section ng-controller='otherCtrl'>
<button ng-click='showDiv()'>show</button>
</section>
Controller:
var otherCtrl = function($scope){
$scope.showDiv = function () {
$scope.visible = true;
};
}
In AngularJS, $scope
s prototypically inherit from their parent scope, all the way up to $rootScope
. In JavaScript, primitive types are overwritten when a child changes them. So when you set $scope.visible
in one of your controllers, the property on $rootScope
was never touched, but rather a new visible
property was added to the current scope.
In AngularJS, model values on the scope should always "have a dot", meaning be objects instead of primitives.
However, you can also solve your case by injecting $rootScope
:
var otherCtrl = function($scope, $rootScope){
$scope.showDiv = function () {
$rootScope.visible = true;
};
}
这篇关于修改从不同的控制器$ rootscope财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!