11

I'm having trouble on figuring out how to pass parameters from my angular controller to service

#my controller  
'use strict';

angular.module('recipeapp')
  .controller('recipeCtrl', ['$scope', 'recipeService',
    function($scope, recipeService){
      $scope.recipeFormData={};
      $scope.recipeSave = function(){
        recipeService.saveRecipe();
      }


  }]);

#my service
'use strict';
angular.module('recipeapp').service('recipeService',['$http', function($http){

  this.saveRecipe = save;

  function save(callback){
     //calling external http api
  }

}]);

What I'm trying to do here is , getting the $scope.formData from my form and controller should pass that to service, As per my understanding, I cannot use $scope inside the service so I need to find a way of passing $scope.formData to the service

tough Idea would be, in the controller, recipeService.saveRecipe($scope.formData); but I'm not sure how to collect that from the service,

when I changed the service this.saveRecipe(val) = save; it doesnt work :(

any help would be appriciated

3
  • Save is undefined when it is assigned to saveRecipe. Put the assignment after the save function. Also, you don't normally need to construct formData manually. Usually one would bind to a model and then pass the model to saveRecipe function Commented Sep 17, 2014 at 3:35
  • Pass your variable as parameter Commented Sep 17, 2014 at 3:35
  • @pixelbits, thanks for the answer.. I have a model which binds the values from the form. what I cannot figure out is how to pass the model to the saveRecipe function in the service ?! Commented Sep 17, 2014 at 3:40

2 Answers 2

20

This example demonstrates the proper structure of an angular app:

  • Model initialization inside your controller
  • Implementation of a service singleton, and injection into your controller
  • Use of $http promises to invoke web API calls asynchronously and allowing callers of your service to handle their success/failure.
  • Use of "controller as" syntax way of exposing functions from your controller rather than exposing functions directly from scope.
  • Two-way data model binding (textbox-to-recipe and recipe-to-textbox)

Initialize your model within your controller:

angular.module('recipeapp')
  .controller('recipeCtrl', ['$scope', 'recipeService',
    function($scope, recipeService){
      // initialize your model in you controller
      $scope.recipe={};

      // declare a controller function that delegates to your service to save the recipe
      this.saveRecipe = function(recipe) {
           // call the service, handle success/failure from within your controller
           recipeService.saveRecipe(recipe).success(function() { 
               alert('saved successfully!!!'); 
           }).error(function(){
               alert('something went wrong!!!');
           });

      }
  }]);

In your recipe service, define the saveRecipe function:

angular.module('recipeapp').service('recipeService',['$http', function($http){

  // expose a saveRecipe function from your service
  // that takes a recipe object
  this.saveRecipe = function(recipe){
      // return a Promise object so that the caller can handle success/failure
      return $http({ method: 'POST', url: '/api/recipe/add', data: recipe});
  }

}]);

Bind your recipe object to your view; add a button to invoke the saveRecipe controller function and save the recipe (passing in the model recipe object):

<div ng-app="recipeapp" ng-controller="recipeCtrl as ctrl">
   <form name="recipeForm">
    Recipe Name: <input type="text" ng-model="recipe.name" />
    <button ng-click="ctrl.saveRecipe(recipe)">Save Recipe</button>
    </form>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

works perfectly , thanks a lot :D, pretty new to angular and still learning :)
1
var module = angular.module('example.service', []);


module.services('ExampleServices', ['$http', '$q', function ($http,
$q) {

    var resourceUrl;

    return {


        setResourceUrl: function(resourceUrl) {
            this.resourceUrl = resourceUrl;
        },



        create: function(params) {
            //access params here sent from controller 
           //make call to server using $http 
           //return back the promise or response
        },



        remove: function(id) {
            //access id here sent from controller 
           //make call to server using $http 
           //return back the promise or response
        }

}

Later in your controller inject the service ExampleServices

And then access:

ExampleServices.create(params)

params could be any object, most probably data captured using forms.

ExampleServices.remove(id)

id could be primary id of the record to be removed from database.

Hope that helps :)

1 Comment

My pleasure @Coder John

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.