我们可以访问工厂里面AngularJS控制器的方法? [英] Can we access controller method inside factory AngularJS?

查看:116
本文介绍了我们可以访问工厂里面AngularJS控制器的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器内的这种方法,我想访问它厂内我穿越功能在出厂时都已注入 $范围变量,我正在从范围内的所有值但这种方法是在控制器中定义的任何帮助AP preciated。

  .factory('viewPdfDocument',['$ SCE,searchService','scrollTop的','pdfPluginDetector','$超时',函数($ SCE,searchService,scrollTop的,pdfPluginDetector,$超时){
    返回{
        pdfView:函数($范围的docId,pdftest,accessForbiddenMessage,genericErrorMessage){
            clearCheckBoxes();
        }
    };
}]);


解决方案

该服务不应该需要知道控制器的细节。你应该能够在其他情况下,重新使用您的服务,而也许是回调到控制器是不同的。

如果是单次回调,说来指示某些活动完成,那么最彻底的方法是使服务方法返回一个承诺,当它要通知控制器解决这个问题。然后回到你采取行动的承诺完成控制器

控制器:

  viewPdfDocument.pdfView(...),那么(clearCheckBoxes)。

这给出了控制器最大的灵活性,它叫。然后()尽可能经常要和不同的功能。

还有余地承诺给正在进行的通知,说来显示progresss酒吧的东西下载。

  viewPdfDocument.pdfView(...),那么(NULL,NULL,的UpdateProgress)。

请注意,如果你想在角使用进度通知,你必须使用旧的 $ q.defer()机制来创建并通知承诺,否则使用ES6兼容机制。

I have this method inside one controller and I want to access it inside factory I already injected $scope variable in factory through function, I am getting all the values from scope except this method which is defined in that controller any help appreciated.

.factory('viewPdfDocument',['$sce','searchService', 'scrollTop', 'pdfPluginDetector', '$timeout',function($sce, searchService, scrollTop, pdfPluginDetector, $timeout) {
    return {
        pdfView: function ($scope, docId, pdftest, accessForbiddenMessage, genericErrorMessage) {
            clearCheckBoxes();
        }
    };
}]);

解决方案

The service should not need to know about the detail of the controller. You should be able to re-use your service in other situations where perhaps that callback to the controller is different.

If it is a single-shot callback, say to indicate completion of some activity, then the cleanest way is to make the service method return a promise and resolve it when it wants to notify the controller. Then back in the controller you act on the completion of the promise

Controller:

 viewPdfDocument.pdfView(...).then(clearCheckBoxes);

This gives maximum flexibility for the controller, it call .then() as often as it wants with different functions.

There is also scope for promises to give ongoing notifications, say to display a progresss bar as something downloads.

 viewPdfDocument.pdfView(...).then(null, null, updateProgress);

Note that if you want to use progress notifications in angular you have to use the old $q.defer() mechanism to create and notify the promise, otherwise use the ES6 compatible mechanism.

这篇关于我们可以访问工厂里面AngularJS控制器的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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