无法设置未定义子对象的属性

时间:2015-05-09 11:54:30

标签: javascript angularjs

当我尝试为我的addressline_1分配一个值时,我无法设置addressline_1的undefined属性,这是一个父对象物理的子对象。感谢是否有人可以告诉我如何解决这个问题?提前谢谢。

$scope.editCompany = function(){
  $scope.submitCompany =[{phone:[]}]; 
  $scope.submitCompany[0].name = "Some Company";
  $scope.submitCompany[0].email = "company@example.com";
  $scope.submitCompany[0].is_active = "TRUE";
  $scope.submitCompany[0].physical.addressline_1 = "77 Example rd";
}

我也试过以下但没有运气。

$scope.editCompany = function(){
  $scope.submitCompany =[{phone:[]},{physical:{addressline_1:"",addressline_2:"",addressline_3:"",addressline_4:"",city:"", region:"",country:"", post_code:""}}]; 
  $scope.submitCompany[0].name = "Some Company";
  $scope.submitCompany[0].email = "company@example.com";
  $scope.submitCompany[0].is_active = "TRUE";
  $scope.submitCompany[0].physical.addressline_1 = "77 Example rd";
}

3 个答案:

答案 0 :(得分:1)

在尝试设置其属性之前,您需要先创建physical对象:

$scope.editCompany = function(){
  $scope.submitCompany =[{phone:[]}]; 
  $scope.submitCompany[0].name = "Some Company";
  $scope.submitCompany[0].email = "company@example.com";
  $scope.submitCompany[0].is_active = "TRUE";
  $scope.submitCompany[0].physical = {};
  $scope.submitCompany[0].physical.addressline_1 = "77 Example rd";
};

或更清晰的语法:

$scope.editCompany = function () {
    $scope.submitCompany = [{
        phone: [],
        name: "Some Company",
        email: "company@example.com",
        is_active: "TRUE",
        physical: {
            addressline_1: "77 Example rd"
        }
    }];
};

答案 1 :(得分:1)

您在设置属性之前将对象分配给physical属性是正确的,但是您将其放在$scope.submitCompany[1].physical而不是$scope.submitCompany[0].physical

physical属性放在与phone属性相同的对象中:

$scope.editCompany = function(){
  $scope.submitCompany = [ { phone: [], physical: {} } ]; 
  $scope.submitCompany[0].name = "Some Company";
  $scope.submitCompany[0].email = "company@example.com";
  $scope.submitCompany[0].is_active = "TRUE";
  $scope.submitCompany[0].physical.addressline_1 = "77 Example rd";
}

答案 2 :(得分:1)

做一些小改变......

$scope.editCompany = function(){
  $scope.submitCompany =[{phone:[]},{physical:{addressline_1:"",addressline_2:"",addressline_3:"",addressline_4:"",city:"", region:"",country:"", post_code:""}}]; 
 ....
  $scope.submitCompany[1].physical.addressline_1 = "77 Example rd"; // instead $scope.submitCompany[0].physical.addressline_1
}