Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : passing params from controller to service

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

like image 597
sameera207 Avatar asked Sep 17 '14 03:09

sameera207


2 Answers

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>
like image 94
pixelbits Avatar answered Sep 21 '22 21:09

pixelbits


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

like image 40
Coder John Avatar answered Sep 21 '22 21:09

Coder John