![](/img/trans.png)
[英]How to send data from child controller to Parent controller in AngularJS?
[英]Push data to parent controller from child [angularjs]
我试图将城市对象推送到父控制器中的数组。 回复是“无法读取未定义的属性'推送”。 无论如何要解决这个问题?
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' }); }
我试图将城市对象推送到父控制器中的数组。 回复是“无法读取未定义的属性'推送”。 无论如何要解决这个问题?
尝试通过$ parent访问它。
function ChildCtrl($scope) {
$scope.$parent.cities.europe.push({
'barcelona', 'madrid', 'manchester'
});
}
在你的代码中:
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控制器中你使用::
function ChildCtrl($scope) {
$scope.cities.europe.push({
'barcelona', 'madrid', 'manchester'
});
}
您将数据推送到europe
对象,但$scope.cities
没有europe
对象。 您可以更改$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'
}]
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.