简体   繁体   English

AngularJS在哪里可以访问已加载控制器的范围?

[英]AngularJS Where can i access the scope of a loaded controller?

Where can i access the scope of a loaded controller ? 在哪里可以访问已加载控制器的范围? I like to have something like a event after the scope has been initialized for a controller to predefine the model for the view. 我希望在初始化控制器的作用域以预定义视图的模型后发生类似事件的事件。

Is there something like $rootScope.$on("$controllerLoaded") 是否有类似$rootScope.$on("$controllerLoaded")

You can do this inside your controller by assigning the value to $scope . 您可以在控制器中通过将值分配给$scope来执行此操作。

function GreetingCtrl($scope) {
    // a simple string
    $scope.greeting = 'Hola!';

    // something more complex
    $scope.myModel = {id:1, name:'bobby'};
}

You could then use this in your view: 然后,您可以在视图中使用它:

<label>{{myModel.name}}</label>

Which would render a label with 'bobby' inside it (until you change your model and then the view is dynamically updated automagically ). 这将在其中呈现带有“ bobby”的标签(直到您更改模型,然后视图会自动动态更新)。

Eventually your application will start to use real world data from a server store of some description and you will need to use either $http or $resource to get at that data. 最终,您的应用程序将开始使用某些描述的服务器存储中的真实数据,并且您将需要使用$ http$ resource来获取该数据。 Check each of the links for examples on how to initialise your model from these modules. 检查每个链接,以获取有关如何从这些模块初始化模型的示例。

Check the Controller documentation for more info 查看控制器文档以获取更多信息

It's not too clear, but it sounds like you want something to notify another part of an app after a particular controller is loaded. 这还不太清楚,但听起来像是您希望某个东西在加载特定控制器后通知应用程序的另一部分。 Is that correct? 那是对的吗?

If so, you have a couple options. 如果是这样,您有两种选择。 Try looking into $emit . 尝试调查$emit Essentially sends a signal to parent listeners. 本质上是向父级侦听器发送信号。

Here is a write-up of using $emit & $broadcast 这是使用$emit$broadcast

$rootScope.$on('emitName', function(){
    //do what you want
});

Another option (more of a hack) would be to set a flag at the end of your controller: 另一个选择(更多的是hack)是在控制器的末尾设置一个标志:

$rootScope.controllerLoaded = true

Then wherever you are wanting to know when it is done, simply check the $rootScope.controllerLoaded flag. 然后,无论您想知道何时完成,都只需检查$rootScope.controllerLoaded标志。

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

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