如何从Angular的服务中调用控制器方法? [英] How to call controller method from service in Angular?

查看:80
本文介绍了如何从Angular的服务中调用控制器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以从服务中调用控制器方法.

I wonder if I can call controller method from service.

我知道Service是单例的,因此无法向该服务注入$scope.

I know that Service is singleton and I can't inject $scope to the service.

就我而言,我在使用中管理Google Maps,并希望在用户右键单击Polygon时打开模式对话框.

In my case I manage Google Maps in service and want to open modal Dialog when user right clicks on Polygon.

据我所知,要打开/创建对话框的新实例,服务必须以某种方式通知控制器以执行此操作.

As I know, to open/create new instance of dialog, somehow Service must notify controller to do that.

这是带有控制器+方法和服务的模板:模板

This is a template with controller + method and service: Template

var myApp = angular.module('myApp', []);        

function MyCtrl($scope,  gridService, $timeout) {    
    // how to call "foo" method from service?
    $scope.foo = function(){
       alert('called from service');
    };     
}

myApp.service('gridService', ['$timeout', function ( $timeout) {       
        var grid = {
                    fetching: false,
                    pristine: true,
                    pageType: 'Edit'
                }       

       return {
            gridSetup: function () {               
               return grid;
            },
           setGridSetup: function (newGrid) {
              }
        } 
}]);

谢谢

推荐答案

通常,您不需要从服务中调用控制器-通常单个服务可以被任何控制器使用,因此服务对此一无所知.在大多数情况下,控制器对服务的调用会响应某些用户的操作,然后您需要在服务完成工作时以某种方式从控制器更新视图(从服务器等获取响应).我看到了以下一般方法.

Usually you do not need to call controller from the service - in general the single service could be used by any controller so service shall know nothing about them. In most cases controller calls to the service in react to some user's action and then you need to update view from controller somehow when service did its work (get response from server, etc.). I see following general ways how to do it.

1.使用回调.

//controller
$scope.onButtonClick = function() {
    $scope.label = "wait, loading...";
    function onSuccess(result) {
        $scope.label = "done! result is " + result;
    }
    myService.doSomeWork(param1, param2, onSuccess);
}


//service
doSomeWork: function(param1, param2, onSuccess) {
    $.get({...}, onSuccess);
}

因此,您为每个操作提供了一个回调.

So you provide a callback for each action.

2.订阅活动 您可以使用jQuery进行事件订阅/触发

2. Subscribe on events You may use jQuery for events subscribing/triggering

//controller
$(myService).on('update', function() {
    $scope.lastUpdateTime = new Date();
});
$scope.onButtonClick = function() {
     myService.doUpdate();
}


//service
doUpdate: function() {
    $.get({...}, function onOk() {
        $(this).trigger('update');
    });
}

3.兑现承诺 许多内置的角度服务返回promise对象,您也可以使用它们:

3. Use promises A lot of built-in angular services return promise objects, you may use them too:

//controller
myService.doSomething(param1).then(function(result) {
    $scope.result = result;
});


//service
doSomething: function(param1) {
    return $http.get({...});
}

4.分享一些数据 一个示例是$resource服务-例如,当您调用query方法时,它将返回空的类数组对象,可以将其安全地放置到作用域中,然后在完成http请求后将其填充值.

4. Share some data An example is $resource service - for example when you call query method it returns empty array-like object that could be safely put to scope and then fills it with values when http request is done.

//controller
$scope.options = myService.options;
$scope.onClick = function() { myService.update() }


//service
options: [],
update: function() {
    var self = this;
    $http.get({...}).success(function(res) {
        self.options.splice(0, self.options.length); //to keep same array
        self.options.push.apply(self.options, res.data.options); 
    });
}

在所有这些情况下,服务和控制器是分开的,服务可以与任何控制器一起使用,并且您可以轻松地对服务进行单元测试,如果您以某种方式更改控制器/视图部件,这些服务不会中断.

In all these cases services and controllers are separated, services could be used with any controller and you may easily write unit-tests on services that will not break if you change your controller/view part somehow.

这篇关于如何从Angular的服务中调用控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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