控制器和工厂中的AngularJS功能在分离时不起作用

时间:2016-11-18 08:43:09

标签: angularjs angularjs-scope ng-repeat ng-controller



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




我需要这么多,请回答一些聪明的事情,我需要的是分离到控制器的服务,还有什么我应该说为什么不发布该死的blalbalblbllbalbalblablalkjvlwakjvnklwavjnlkwanvwanviwbilawvwavawvas vasvklwanvljabwjkabwv

2 个答案:

答案 0 :(得分:1)

return {getData}在服务

中的语法不正确
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
   };

答案 1 :(得分:0)

将您的工厂从angular.module('myFirstApp',[]).factory更改为angular.module('myFirstApp').factory,即使用angular.module('myFirstApp')但不使用angular.module('myFirstApp', [])