在 Angular 的 run() 方法中获取 $scope 对象 [英] Getting $scope object in Angular's run() method

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

问题描述

我想在我的应用加载时做一些事情来设置默认状态.所以我试图在 Module 对象上使用 run 方法.当我尝试访问 $scope 变量时,尽管我在控制台中收到一条未捕获的 ReferenceError:$scope 未定义"消息.

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.

看下面的例子http://jsfiddle.net/F2Z2X/1/

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

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

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

我是不是说错了?

例如,我想在开始时运行 watchAction 函数一次,以隐藏尚未调用的 UI 元素,但是 watchAction 函数没有 $scope 对象,因为它没有被 watch 调用方法,所以我必须将它传递给它,但可惜它不可用.

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"};
});

你只能将$rootScope注入到servicesrun函数中,因为每个child scope都是继承的从其父作用域开始,顶级作用域是 rootScope.因为注入 any 范围是不明确的.仅提供根范围.

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.

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

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