如何从控制器调用服务方法?

mem*_*und 0 javascript angularjs

我有一个service和一个controller.如何在服务中定义一个可以由控制器调用的方法(传递一个值)?

以下不起作用:

angular.module('test').service('myService', function() {
    this.updateContent = function(selection) {
        alert(selection);
    };

    return {
        //required for some databinding
        model: [
             someProperty = null;
        ]
    };
});

angular.module('test').controller('testController', ['$scope', 'myService', function($scope, myService) {
    $scope.updateSelection = function() {
        myService.updateContent("test");
    }
}]);
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以在return语句中包含该函数:

    return {
        //required for some databinding
        updateContent: this.updateContent,
        model: [
             someProperty = null
        ]
    };
Run Code Online (Sandbox Code Playgroud)