从不同的控制器修改 $rootscope 属性 [英] Modify $rootscope property from different controllers

查看:20
本文介绍了从不同的控制器修改 $rootscope 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 rootscope 中,我有一个 visible 属性,它控制 div 的可见性

app.run(function ($rootScope) {$rootScope.visible = false;});

示例 HTML:

<button ng-click='toggle()'>toggle</button><div ng-show='visible'><button ng-click='toggle()'>&times;</button>

</节>

控制器:

var oneCtrl = function($scope){$scope.toggle = 函数 () {$scope.visible = !$scope.visible;};}

以上部分工作正常,元素显示或隐藏没有问题.现在在不同部分的同一页面中,我尝试更改 visible 变量以显示 div,但它不起作用.

<button ng-click='showDiv()'>show</button></节>

控制器:

var otherCtrl = function($scope){$scope.showDiv = 函数 () {$scope.visible = true;};}

解决方案

在 AngularJS 中,$scope 的原型通常从它们的父作用域继承,一直到 $rootScope.在 JavaScript 中,当子项更改原始类型时,它们会覆盖.因此,当您在其中一个控制器中设置 $scope.visible 时,$rootScope 上的属性从未被触及,而是一个新的 visible 属性已添加到当前范围.

在 AngularJS 中,作用域上的模型值应该总是有一个点",意思是对象而不是基元.

但是,您也可以通过注入 $rootScope 来解决您的问题:

var otherCtrl = function($scope, $rootScope){$scope.showDiv = 函数 () {$rootScope.visible = true;};}

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()'>&times;</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, $scopes 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 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆