Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wonder if I can call controller method from service.

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

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) {
              }
        } 
}]);

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
164 views
Welcome To Ask or Share your Answers For Others

1 Answer

The answer is simple: you don't.

The service exists to manipulate data, nothing else. And it really shouldn't care "why" it's doing what it's doing. You ask the service to do something and wait for a response.

Personally I prefer using promises to resolve async operations (i.e. to notify the controller about a state change) since it's heavily supported by many angular services like $http. But feel free to use callbacks of you wish.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...