Rectangle 27 0

AngularJS : passing params from controller to service?


<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>
angular
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!!!');
           });

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

}]);
  • Implementation of a service singleton, and injection into your controller
  • Use of "controller as" syntax way of exposing functions from your controller rather than exposing functions directly from scope.
  • Use of $http promises to invoke web API calls asynchronously and allowing callers of your service to handle their success/failure.

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):

In your recipe service, define the saveRecipe function:

This example demonstrates the proper structure of an angular app:

Note
Rectangle 27 0

AngularJS : passing params from controller to service?


ExampleServices.create(params)
ExampleServices.remove(id)
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
        }

}

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

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

Note