1

Whenever I run the app implemented by angularjs 1.4.3.

BannerService.js

app.service('BannerService',function ($http) {

    this.save = function saveBanner(banner) {
        return $http({
              method: 'POST',
                url: 'http://localhost:8081/api/banners'
            });
    }

});

BannerController.js

app.controller('BannerAddCtrl', ['$scope','$log','BannerService',
    function ($scope,$log, BannerService) {
        $scope.save = function() {
            BannerService.saveBanner(myBanner)
                .success(function (result) {
                    $log.debug('RESULT', result);
                }, function (reason) {
                    $log.debug('REASON', reason);
                });
        }

}]);

And index.html

 <div class="modal-footer">
    <button type="button" class="btn btn-primary btn-block" ng-click="save()">Save Banner</button>

  </div>

It throws an exception as below:

TypeError: BannerService.saveBanner is not a function
at ChildScope.$scope.save (bannerControllers.js:64)
at fn (eval at compile (angular.js:13145), <anonymous>:4:203)
at callback (angular.js:23298)
at ChildScope.$eval (angular.js:15846)
at ChildScope.$apply (angular.js:15945)
at HTMLButtonElement.<anonymous> (angular.js:23303)
at HTMLButtonElement.dispatch (jquery.js:4435)
at HTMLButtonElement.elemData.handle (jquery.js:4121)

Can someone help me why I get the error. Greatly appreciate your time.

3 Answers 3

8

Take a look at the error message:

BannerService.saveBanner is not a function

Basically, your app is looking for the property saveBanner assigned to your Service. But currently you haven't declared such a property. Instead your Service contains a property called save which defines a function (called saveBanner).

AngularJS doesn't care about a named function which is assigned to a property. So instead, you've to adjust the propertyname itself. So your Service's function/property should be like this.

this.saveBanner = function () { ... }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it is useful to me.
Glad I could help. Getting marked as correct answe would be nice though. :)
0

Write your service like below.

var self = this;
self.saveBanner = function () { ... }

Comments

0

You're save function in the controller isn't actually calling the function in your service.

app.service('BannerService',function ($http) {
        return {
          saveBanner: function(banner) {
                return $http({
                      method: 'POST',
                        url: 'http://localhost:8081/api/banners'
                    });
                  }
               }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.