我试图将城市对象推送到父控制器中的数组。答复是“无法读取未定义的属性'push'”。无论如何要解决这个问题?

ChildCtrl嵌套在ParentCtrl中。



<!DOCTYPE html>
<html lang="en" ng-app="citieApp">

<body>
  <div class="container">
    <div ng-controller="ParentCtrl">
      {{cites to be listed here ON UPDATE from the child controller}}


      <div ng-controller="ChildCtrl">
        <form>
          <!--This inputs are to insert cities-->
          <input type="text">
          <input type="text">
          <input type="text">
          <button>Submit Cities</button>
        </form>
      </div>
    </div>
  </div>
</body>

</html>







function ParentCtrl($scope) {
  $scope.cities = [{
    america: [{
      'alberta', 'NY', 'chicago', 'LA'
    }, {
      'atlanta', 'New town', 'boston', 'boulder'
    }, {
      'dallas', 'austin', 'denver', 'colombus'
    }]
  }, {
    europe: [{
      'london', 'paris', 'Helsinki'
    }, {
      'berlin', 'rome', 'tallin'
    }, {
      'lisbon', 'amsterdam', 'brussels'
    }]
  }];
};

function ChildCtrl($scope) {
  $scope.cities.europe.push({
    'barcelona', 'madrid', 'manchester'
  });
}





我试图将城市对象推送到父控制器中的数组。答复是“无法读取未定义的属性'push'”。无论如何要解决这个问题?

最佳答案

在您的代码中:

  function ParentCtrl($scope) {
     $scope.cities = [{
         america: [{
            'alberta', 'NY', 'chicago', 'LA'
         }, {
            'atlanta', 'New town', 'boston', 'boulder'
          }, {
            'dallas', 'austin', 'denver', 'colombus'
          }]
       }, {
          europe: [{
             'london', 'paris', 'Helsinki'
           }, {
         'berlin', 'rome', 'tallin'
         }, {
            'lisbon', 'amsterdam', 'brussels'
        }]
  }];
};


这里,

 $scope.cities[0] = {
         america: [{
            'alberta', 'NY', 'chicago', 'LA'
         }, {
            'atlanta', 'New town', 'boston', 'boulder'
          }, {
            'dallas', 'austin', 'denver', 'colombus'
          }]
       };


  $scope.cities[1] = {
        {
          europe: [{
             'london', 'paris', 'Helsinki'
           }, {
         'berlin', 'rome', 'tallin'
         }, {
            'lisbon', 'amsterdam', 'brussels'
        }]
   };


但是在clild Controller中,您使用::

   function ChildCtrl($scope) {
      $scope.cities.europe.push({
         'barcelona', 'madrid', 'manchester'
      });
   }


您将数据推入europe对象,但是europe对象在$scope.cities中不可用。您可以按如下所示更改$scope.cities

  $scope.cities = {
         america: [{
            'alberta', 'NY', 'chicago', 'LA'
         }, {
            'atlanta', 'New town', 'boston', 'boulder'
          }, {
            'dallas', 'austin', 'denver', 'colombus'
          }], {
          europe: [{
             'london', 'paris', 'Helsinki'
           }, {
              'berlin', 'rome', 'tallin'
           }, {
            'lisbon', 'amsterdam', 'brussels'
          }]
  };

09-19 19:43