$ rootScope不是在工厂/服务定义 [英] $rootScope not defined in a factory / service

查看:126
本文介绍了$ rootScope不是在工厂/服务定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个code是这样的:

I have a code like this:

    angular.module('app')
    .factory('ME', function($http, $location, $rootScope){

       return {
        search: function(search_data, success, $rootScope) {
           $rootScope.errors = "lalala";
        }
       }
    });

,当我调用一个函数搜索(),当我调试,我得到一个错误,指出 $ rootScope 是不确定的。怎样使一个用 $ rootScope 在一个工厂?

And when I am calling a function search() and when I debug, I get an error saying that $rootScope is undefined. How do I make a use of $rootScope in a factory?

推荐答案

在回答我的问题在于我对这个问题的第一注释中。为了清除此消息您将需要删除 $ rootScope 搜索函数参数。 - 功能(search_data,成功,$ rootScope)这就是被清理的结果。

The answer to my question lies within my first comment on the question. In order to clear this message you would need to delete a $rootScope from a search function arguments. - function(search_data, success, $rootScope). That is what is clearing the results.

不过,我想后更多的东西,这是一条评论,这种做法应该被修改,可能不是首先使用root范围。在这种情况下,也许应该,因为我们设置一个错误信息,但如果是其他任何值,那么你应该摆脱 $ rootScope 并添加局部变量,可以从一个功能的方法稍后返回。像这样的:

But I wanted to post something more, and that is a comment that this approach should be modified and probably not to use the root scope in the first place. In this case it probably should, as we are setting an error message, but if it would be any other values then you should get rid of the $rootScope and add local variables, that can be later returned from a function method. Like this:

 angular.module('app')
    .factory('ME', function($http, $location, $rootScope){

       var result;

       return {
        search: function(search_data, success) {
           result = "lalala";
        },
        update: function(){
           result = "tralala";
        },

        message: function(){return result;} 
       }
    });

我加入这个作为进一步解释,因为一般我希望得到更好地了解何时以及如何使用 rootScopes

这篇关于$ rootScope不是在工厂/服务定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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