我可以在工厂内访问控制器中定义的方法,如$ rootscope.method()吗?

时间:2016-02-15 11:04:33

标签: angularjs

如何访问工厂内的控制器方法。

        //controller.js
        $rootScope.stackTraceReport = function(error){
            var exception = errorHandler(error);
            //reproting to server
            StackTrace.report(exception,serviceUrl);
        }

      // factory.js
     .factory('viewPdfFailure',['scrollTop', '$timeout', function(scrollTop, $timeout) {
    return {
        viewError: function ($scope, $rootScope, data, status, headers, config, accessForbiddenMessage, genericErrorMessage) {
            $timeout(function () {
                $scope.errorMessages = [];
                $scope.infoMessages = [];
            }, 7000);
            console.error('Error in viewDocument, status: ' + status);
            if (status == 403) {
                $scope.errorMessages.push(accessForbiddenMessage);
                scrollTop.onErrorScrollTop('id-header');
            } else {
                $scope.errorMessages.push(genericErrorMessage);
                scrollTop.onErrorScrollTop('id-header');
            }
            $rootScope.stackTraceReport(data);
        }

帮我弄清楚如何在工厂内访问这个控制器方法。我得到方法未定义错误。我是否需要在工厂内注入控制器?

2 个答案:

答案 0 :(得分:0)

我认为您遇到此错误,因为当您调用public class GridAdapter extends BaseAdapter { private Context mContext; private ArrayList<String> list; public ListAdapter(Context context,ArrayList<String> posters){ this.mContext = context; this.list = posters; notifyDataSetChanged(); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view=null; ImageView imageView; if (convertView == null) { view = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false); imageView = (ImageView) view.findViewById(R.id.list_image); } else { imageView = (ImageView) convertView; } Picasso.with(mContext).load(posters.get(position)).into(imageView); return view; } } 方法时,您没有定义它(调用$rootScope.stackTraceReport(data);)。

确保首先调用函数定义(你可以放两个$rootScope.stackTraceReport = function(error){...}来看第一个调用函数。

但我认为你创建一个单独的Util工厂来制造所有这些&#34;全局&#34;函数是同一个文件,并确保在调用它时定义函数。 (http://blog.jdriven.com/2013/03/how-to-create-singleton-angularjs-services-in-4-different-ways/

答案 1 :(得分:0)

该方法应该在run方法中定义,以便在其他地方使用它:

代码:

.run(['$rootScope', 'StackTrace', function ($rootScope, StackTrace) {
    $rootScope.stackTraceReport = function (error) {
        var exception = errorHandler(error);
        //reproting to server
        StackTrace.report(exception, serviceUrl);
    }
}]);