AngularJS function in controller and factory not working when separated

为君一笑 提交于 2019-12-25 18:41:14

问题


angular.module('myFirstApp')// 
//begin controller
.controller('myController',function($scope,$http,personFactory){ //hi im controller i need to call the http service from the factory 
  
  //begin service
  //hi im service i dont want to live in controller.js , i want to live in app.js
  //can we put the service inside a factory which is in app.js file and get called using controller #1
   $http.get('iphone.json').success(function(result){
    $scope.ObjectArray = result;
    
  }).error(function(error){
    alert(error.error + "/" + error.statusCode);
  }); //end
 
  
  //begin
  // hi i am controller #1 , i live in controller.js , i need to call http service in factory and send the value to HTML
   $scope.retrieveRecords = function(){
    var x = personFactory.getData();
    return x 
  }//end
  
  
  // i am controller #2
  $scope.addRecord = function(){
    var x = personFactory.insertData($scope.Name,$scope.Email,$scope.Password,$scope.Mobile,$scope.result);
    $scope.message = "You have successfuly added new data";
    return x + ' ' + $scope.message;
  }
  
  // i am controller #3
  $scope.editRecord = function(){
    var x = personFactory.updateData();
    $scope.message = "You have successfuly updated the data";
  return x + ' ' + $scope.message;
  }


})

//end controller

//begin factory
.factory('personFactory',function(){ //hi im factory i live in app.js , im waiting for http service to live here
  //end factory

what i need so much , please answer with something clever, all i need is the service separated to controller , what else should i say why is not posting damn blalbalblbllbalbalblablalkjvlwakjvnklwavjnlkwanvwanviwbilawvwavawvas vasvklwanvljabwjkabwv


回答1:


Change your factory from angular.module('myFirstApp',[]).factory to angular.module('myFirstApp').factory i.e., use angular.module('myFirstApp') but not angular.module('myFirstApp', [])




回答2:


return {getData} is not right syntax in service

angular.module('myFirstApp',[])
.factory('personFactory',function(){

    function getData(){       
      var x = $http.get('iphone.json').success(function(result){
      $scope.items = result;
      alert(result);
      }).error(function(error){
      alert(error.error + "/" + error.statusCode);
      })    
      return x;
    }
  return {
      getData: getData
   };


来源:https://stackoverflow.com/questions/40672668/angularjs-function-in-controller-and-factory-not-working-when-separated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!