AngularJS:如何将参数从控制器传递到工厂

时间:2018-06-21 03:01:35

标签: angularjs

我有两个HTML代码和两个控制器,我知道数据可以从工厂传递/共享到多个控制器。第一个html代码是用户要填写的表单。第二个html代码是从第一个html代码获取数据。

我了解可以通过工厂中的$ http get服务来完成。

我的问题是如何获取HTML页面的API或该页面的控制器的API?

4 个答案:

答案 0 :(得分:1)

  

创建服务

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

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

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

//或者,您也可以创建一个工厂。

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

//对于View:HTML-1,控制器: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); 
 }]);
  

对于View:HTML-2,控制器: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"}
  }]);

答案 1 :(得分:0)

如果您正在使用Angular1.X,那么它就很简单。

请使用此代码段

由于angularJS是一个单页应用程序,因此,您必须在index.html中包含该公共服务,并在各自的控制器中包含该公共服务

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

答案 2 :(得分: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;
                }
    };
    });

----从Controller调用上述服务-

答案 3 :(得分:0)

只要有人感兴趣,我就想出了另一种方法。 1.将数据发布到数据库。在这种情况下,使用的数据库是“ Firebase”。 2.从数据库中检索数据。

不同之处在于,我不是将数据从一项服务传递到另一项服务,而是将数据发布到Firebase并进行检索。

将数据发布到Firebase的代码: 1.创建服务。

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

从Firebase检索数据的代码:

  1. 服务。 (与上述服务相同。)

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

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