2016-10-25 3 views
0

私のリストがサービス中の配列リストに新しいオブジェクトをプッシュするには?angularjs - (サービス内の)私のリストに新しいオブジェクトを(スコープとして)プッシュ

私のコントローラには、私のリストにオブジェクトの新しいレイヤをプッシュする機能がありますが、リストの配列をサービスとして新しいファイルに移動してからです。それはもう働きません。

コントローラー:

$scope.addContact = function() { 
     $scope.person.contact.push({ 
      contactType: "", 
      contactNumber: "" 
     });    
    }; 

サービス:私は "addContact" それは私のリストに新しいオブジェクトを ".push" になる

angular 
    .module("person") 
    .service("InitService", initializeItem); 

function initializeItem() { 

    var self = this; 

    self.ReturnInit = function() { 
     var person = { 
      firstname: "", 
      lastname: "", 
      address: [ 
       { 
        addresstype: "", 
        addresslocation: "" 
       } 
      ], 
      contact: [ 
       { 
        contacttype: "", 
        contactnumber: "" 
       } 
      ] 
     }; 

     return person; 

    }; 

}; 

毎回。

この探している:

person = { 
     firstname: "", 
     lastname: "", 
     address: [ 
      { 
       addresstype: "", 
       addresslocation: "" 
      },{ 
       addresstype: "", 
       addresslocation: "" 
      } 
     ], 
     contact: [ 
      { 
       contacttype: "", 
       contactnumber: "" 
      } 
     ] 

答えて

1

あなたはあなたのサービスの上位レベルに人のVARを移動し、このようにそれを使用することができます。

サービス:

angular 
    .module("person") 
    .service("InitService", initializeItem); 

function initializeItem() { 

    var self = this; 
    var person = { 
     firstname: "", 
     lastname: "", 
     address: [{ 
      addresstype: "", 
      addresslocation: "" 
     }], 
     contact: [{ 
      contacttype: "", 
      contactnumber: "" 
     }] 
    }; 

    self.ReturnInit = function() { 
     return person; 

    }; 
    self.addContact = function(contact) { 
     person.contact.push(contact); 
    } 
}; 

はコントローラー:あなたのコントローラで

$scope.addContact = function() { 
    InitService.addContact({ 
     contactType: "", 
     contactNumber: "" 
    }); 
}; 
0

$scope.personInitService

$scope.person = InitService.ReturnInit(); 
$scope.addContact = function() { 
     $scope.person.contact.push({ 
      contactType: "", 
      contactNumber: "" 
     });    
    }; 
によって返されたオブジェクトを参照します
関連する問題