简体   繁体   English

如何从组件访问 $rootScope?

[英]How do I reach $rootScope from a component?

I am very new to AngularJS/Ionic/Cordova programming and am trying to handle the visibility of a component using a global variable, so it can be hidden or shown from other components.我对 AngularJS/Ionic/Cordova 编程非常陌生,我正在尝试使用全局变量处理组件的可见性,因此它可以从其他组件中隐藏或显示。 I am creating the variable when calling the run function, assigning it to $rootScope .我在调用run函数时创建变量,将其分配给$rootScope

app.run(function($rootScope, $ionicPlatform) {
    $ionicPlatform.ready(function() {
        // Some Ionic/Cordova stuff...

        // My global variable.
        $rootScope.visible = true;
    });
})

My component is:我的组件是:

function MyComponentController($rootScope, $scope) {
    var self = this;
    self.visible = $rootScope.visible;
    alert(self.visible);
}

angular.module('myapp')
    .component('myComponent', {
        templateUrl: 'my-component.template.html',
        controller: MyComponentController
    });

And the template:和模板:

<div ng-if="$ctrl.visible">
  <!-- ... -->
</div>

However the alert message always shows "undefined".但是,警报消息始终显示“未定义”。 What am I missing?我错过了什么?

$rootScope.visible isn't watched when being assigned as self.visible = $rootScope.visible . $rootScope.visible在被分配为self.visible = $rootScope.visible时不被self.visible = $rootScope.visible And it is undefined at the moment when component controller is instantiated.并且在组件控制器实例化时它是undefined的。

It can be有可能

function MyComponentController($rootScope, $scope) {
    var self = this;

    $scope.$watch(function () { return $rootScope.visible }, function (val) { 
        self.visible = val;
    });
}

By the way, it is likely available as $scope.$parent.visible and can be bound in template as ng-if="$parent.visible" , but this is antipattern that is strongly discouraged.顺便说一下,它可能作为$scope.$parent.visible可用,并且可以作为ng-if="$parent.visible"绑定在模板中,但这是强烈不鼓励的反模式。

There may be better approaches:可能有更好的方法:

  • top-level AppController and <my-component ng-if="visible"> , so the component doesn't have to control its own visibility顶级AppController<my-component ng-if="visible"> ,因此组件不必控制自己的可见性

  • broadcasting it with scope events, $rootScope.$broadcast('visibility:myComponent')用范围事件广播它, $rootScope.$broadcast('visibility:myComponent')

  • using a service as event bus (that's where RxJS may be helpful)使用服务作为事件总线(这就是 RxJS 可能有用的地方)

  • using a router to control the visibility of views, possibly with route/state resolver (this is the best way)使用路由器来控制视图的可见性,可能使用路由/状态解析器(这是最好的方法)

How about change self to $scope like this:像这样将self更改为$scope怎么样:

function MyComponentController($rootScope, $scope) {
    $scope.visible = $rootScope.visible;
    alert($scope.visible);
}

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

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