0

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?

4 Answers 4

1

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"}
  }]);
Sign up to request clarification or add additional context in comments.

3 Comments

"const obj = {}" can I make it a var instead of a const?
The code is correct, you need to ensure you're swapping the variable names for your own and then binding those same names in the respective templates. This is angular101 stuff, I suggest going through some tutorials to ensure you understand the concepts a bit better.
@Chad H replace all my codes with his including changing all my variables.
0

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)

2 Comments

@an33sh Which means I just need to copy and paste the code directly into the index.html and its respective controller? What about the factory? Also, how is this going the pass the user input data from the form(index.html) to the factory?
Which means I just need to copy and paste the code directly into the index.html and its respective controller? What about the factory? Also, how is this going the pass the user input data from the form(index.html) to the factory?
0
 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--

Comments

0

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

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.