获得$范围对象角的run()方法 [英] Getting $scope object in Angular's run() method

查看:107
本文介绍了获得$范围对象角的run()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做一些东西时,我的应用程序加载设置默认状态。所以我试图用run方法模块对象。当我尝试,虽然我得到一个访问$范围的变量:在我的控制台未捕获的Ref​​erenceError $范围没有定义消息

请参阅下面的例子 http://jsfiddle.net/F2Z2X/1/

 应用程序= angular.module('MyApp的',[]);app.controller('myController的',函数($范围){
    $ scope.data = {MYVARIABLE:'你好'};
});app.run(
    警报($ scope.data.myvariable))
);

我要对所有这一切错了?

例如,我想在开始运行一次watchAction功能,隐藏未呼吁尚未UI元素,但watchAction功能不具备$范围,对象,因为它不是由所谓的手表方法,所以我必须把它传递给它,但可惜它是不可用的。


解决方案

  app.run(函数($ rootScope){
    $ rootScope.someData = {消息:你好};
});

您只能获得 $ rootScope 注入服务运行函数,因为每个子范围是从它的父作用域继承和顶层范围 rootScope 。由于这将是ambigous注入的任何的范围。只有root范围提供。

I'd like to do some stuff when my app loads to set up the default state. So I'm trying to use the run method on the Module object. When I try to access the $scope variable though I get an "Uncaught ReferenceError: $scope is not defined" message in my console.

See the following example http://jsfiddle.net/F2Z2X/1/

app = angular.module('myapp', []);

app.controller('mycontroller', function($scope){
    $scope.data = { myvariable: 'Hello' };
});

app.run(
    alert($scope.data.myvariable))
);

Am I going about this all wrong?

For example, I want to run the watchAction function once at the beginning, to hide UI elements that aren't called for yet, but the watchAction function doesn't have the $scope object because it's not being called by the watch method so I have to pass it to it, but alas it's not available.

解决方案

app.run(function ($rootScope) {
    $rootScope.someData = {message: "hello"};
});

You can only get $rootScope injected to services and run function, because each child scope is inherited from its parent scope and the top level scope is rootScope. Since it would be ambigous to inject any scope. Only root scope is provided.

这篇关于获得$范围对象角的run()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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