[英]AngularJS - append data to json array
I am stuck in one scenario where i have to pass data from one controller to another controller. 我陷入一种情况,我必须将数据从一个控制器传递到另一个控制器。
My app works like this: 我的应用程序如下所示:
View 1 -> gets some users from json array and displays in a table. 视图1->从json数组中获取一些用户并显示在表中。
When i click add user in View 1, i get redirected to view 2. 当我在视图1中单击添加用户时,我将重定向到视图2。
View 2 -> has 2 input fields and a button (to add a new user). 视图2->具有2个输入字段和一个按钮(用于添加新用户)。
When i redirect to view 1, i want the new user to get appended but this is not working. 当我重定向到视图1时,我希望新用户能够被追加,但这不起作用。
To make it easy, i have demoed this here - http://plnkr.co/edit/yz6mpplZGh4q5bPDO2bc?p=preview 为了简单起见,我在这里进行了演示-http://plnkr.co/edit/yz6mpplZGh4q5bPDO2bc? p=preview
Any help is much appreciated. 任何帮助深表感谢。
View2
directive needs to define that it requires View1
. View2
指令需要定义它需要View1
。 This will tell Angular to pass the controller for View1
as an argument to View2
's controller. 这将告诉Angular将
View1
的控制器作为参数传递给View2
的控制器。
You can then call a method addUser(..)
on that controller. 然后,您可以在该控制器上调用方法
addUser(..)
。
https://docs.angularjs.org/guide/directive#creating-directives-that-communicate https://docs.angularjs.org/guide/directive#creating-directives-that-communicate
You are always overwriting the 'users' content on entry of the list controller. 您总是在进入列表控制器时覆盖“用户”内容。
Change your controller to 将您的控制器更改为
...
controller('UserController', function($scope,UserService){
if (!$scope.users)
{
UserService.getUsers().then(function(data){
$scope.users = data;
})
}
...
And bring back your 'correct' 并带回您的“正确”
$scope.users.push($scope.user)
in your addUserController. 在您的addUserController中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.