user9739730
user9739730

Reputation: 21

AngularJS : How to pass parameter from controller to factory

I have two HTML code and two controller, I know data can be passed/shared from the factory to multiple controllers. The first html code is a form to be fill up by the users. The second html code is to get data from the first html code.

I understand the can be done through the $http get service in the factory.

My question is how do I get the API of my HTML page or the API of the controller for that page?

Upvotes: 0

Views: 256

Answers (4)

user9739730
user9739730

Reputation: 21

Just so if anyone will be interested, I figured out another method. 1. Post data to a database. In this case, the database is used is "Firebase". 2. Retrieve the data from the database.

Whats different is that instead of passing data from one service to another, i am posting the data the firebase and retrieving it.

Codes to POST data to firebase: 1. create a service.

angular.module('firebaserequest', ['firebase'])
.factory('requestService', ['$firebaseArray',
function($firebaseArray){ 
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
if(!firebase.apps.length){
firebase.initializeApp(config);
}

var ref = firebase.database().ref().child("");
var requestArray = $firebaseArray(ref);
return {

add: function(name, date, department, status0, status1, status2, status3, status4) {

  // Transform Date to string

  var requestItem = { 
      Name:name,
      Date:date.toDateString(),
  };
  requestArray.$add(requestItem);

  },
  1. controller

    .controller('Ctrl', ['$scope', '$stateParams', 'requestService',
    function ($scope, $stateParams, requestService) {
    $scope.request = {
      name:null,
      date:new Date(),
      status0:null,
      status1:null,
      status2:null,
      status3:null,
      status4:null,
     };
    
    $scope.refreshCreate = function() {
    
    $scope.request = {
      name:null,
      date:new Date(),
    }; 
    $scope.$broadcast('scroll.refreshComplete');
    } 
    //Function to "create" request & alert    
    $scope.alert = function() {
    alert(")!"
      + $scope.request.name
      )
    
     requestService.add(
      "",
      $scope.requestt.name,
      $scope.requestt.date,
      "submitted",
      "pending",
      "pending",
      "pending",
      "pending",);
     $scope.refreshCreate();
     }
     }])
    

Codes to retrieve data from firebase:

  1. Services. (In the same services as the one above.)

    getPending: function() {
    var query = ref.orderByChild("Approval0").equalTo("submitted");
    var pendingArray = $firebaseArray(query); 
    return pendingArray.$loaded().then(function() { 
    return pendingArray;
    });
    },
    
  2. controller

    .controller('Ctrl', ['$scope', '$stateParams', 'requestService',
    function ($scope, $stateParams, requestService) {
    $scope.refresh = function(){
    requestService.getPending()
    .then(function(result){
        $scope.requestArray = result; 
    })
    .finally(function(){
     $scope.$broadcast('scroll.refreshComplete');
    });
    }
    $scope.refresh();
    $scope.getIconClass = function(item) {
    if (item.Approval4 == "Approved")
    return "balanced ion-checkmark-circled";
    else if (item.Approval1 == "Rejected")
    return "assertive ion-close-circled";
    else if (item.Approval2 == "Rejected")
    return "assertive ion-close-circled";
    else if (item.Approval3 == "Rejected")
    return "assertive ion-close-circled";
    else if (item.Approval4 == "Rejected")
    return "assertive ion-close-circled";  
    else
    return "energized ion-android-stopwatch";
    }
    }]) 
    

Upvotes: 0

Krutivas Mohapatra
Krutivas Mohapatra

Reputation: 1

 You have to create service like below and use it in your controller 
 Service code :
    APP(your app name).factory('commonService', function() 
    {
         var storedObject;
            return {
                set: function(o) {
                    this.storedObject = o;
                },
                get: function() {
                    return this.storedObject;
                }
    };
    });

----Call the above service from Controller--

Upvotes: 0

Vaibhav Shitole
Vaibhav Shitole

Reputation: 79

Create a Service

angular.module('XYZ').service("XyzService", ["", function() {
  this.data = undefined;    

  this.getData() {
      return this.data; 
  }

  this.setData(dataObject) {
      this.data = dataObject; 
  }
 }]);

// Or, you can create a factory as well.

angular.module('XYZ').factory('XyzFactory', ["", function () {
  const obj = {};
  obj.data = undefined;
  obj.getData = function () {
      return obj.data;
  };
  obj.setData = function (dataObject) {
      obj.data = dataObject;
  };
  return obj; 
}]);

//For View: HTML-1, Controller: View1Controller

angular.module('XYZ').controller("View1Controller", ["$scope", "XyzService", "XyzFactory", function($scope, XyzService, XyzFactory) {

  // Here you can set data in the XyzService. e.g.
  $scope.dataObject = {
      "firstName" : "John",
      "lastName"  : "Parker"
  };
  // Using service.
  XyzService.setData($scope.dataObject);

  // Using factory
  XyzFactory.setData($scope.dataObject); 
 }]);

For View: HTML-2, Controller: View2Controller

angular.module('XYZ').controller("View2Controller", ["$scope", "XyzService", "XyzFactory", function($scope, XyzService, XyzFactory) {

  // Here, you can access data Using service.
  console.log("ACCESS DATA : " + XyzService.getData());
  // {"firstName" : "John", "lastName" : "Parker"}

  // Here, you can access data Using factory.
  console.log("ACCESS DATA : " + XyzFactory.getData());
  // {"firstName" : "John", "lastName" : "Parker"}
  }]);

Upvotes: 1

Krutivas Mohapatra
Krutivas Mohapatra

Reputation: 1

If you are working on Angular1.X, then its simple.

Please use this snippet code

As angularJS is a single page application, therefore, you have to include that common service in index.htmland include that common service in your respective controller

app.controller('testController', ['$scope','commonServices',',function($scope,commonServices)

Upvotes: 0

Related Questions