0

I wanna make "Go back when cancel btn clicked" function.

This is view code

<div ng-controller="goodCtrl">    
<button class="btn" ng-click="cancel()">Cancel</button>
</div>

And this is Js code

1) controller

function goodCtrl($scope, $log, goodService)
    $scope.cancel = function(){
        $log.debug("goodCtrl - cancel");
        goodService.cancel($scope);
    };

2) service

function goodService($log, $state)
    var methods = {
       cancel: function($scope) {
           $log.debug("goodService - cancel");
           $state.go('goback');
       }
    }

3) module

angular
    .module('goodmodule')
    .controller('goodCtrl', goodCtrl)
    .service('goodService', goodService)

But I got this problem

TypeError : serviceName.functionName() is not a function

Though there are so many controls, services, methods written like that, the service and controller that I added is unavailable. What is it that I missed?

ayushgp
  • 4,891
  • 8
  • 40
  • 75
zzangs33
  • 197
  • 1
  • 15
  • Is that literally the error message? Don't see anything in your code that looks like that – Phil Mar 27 '18 at 06:13

2 Answers2

1

As you have defined service register methods to be exposed using using this

function goodService($log, $state) {
    this.cancel = function ($scope) {
        $log.debug("goodService - cancel");
        $state.go('goback');
    }
}

I would also recommend you to use Dependency Annotation, Here I have used $inject property annotation

 goodCtrl.$inject = ['$scope', '$log', 'goodService'];
 goodService.$inject = ['$log', '$state'];
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • I solved problem! it occurs because of not returning methods. thanks! – zzangs33 Mar 28 '18 at 00:26
  • 1
    @zzangs33, then you should define it as a `factory` see https://stackoverflow.com/questions/14324451/angular-service-vs-angular-factory – Satpal Mar 28 '18 at 06:01
1

In angularjs, to define a service, you have to assign properties in this keyword within service function. Because in angular js constructor function is used to create a custom service.Below code is your updated service code.

    function goodService($log, $state) {
    this.cancel = function ($scope) {
        $log.debug("goodService - cancel");
        $state.go('goback');
    }
}
Chinmoy Samanta
  • 1,376
  • 7
  • 17