AngularJS -追加数据到json数组

AngularJS - append data to json array

本文关键字:json 数组 数据 追加 AngularJS      更新时间:2023-09-26

我被困在一个场景中,我必须将数据从一个控制器传递到另一个控制器。

我的应用程序是这样工作的:

视图1 ->从json数组中获取一些用户并显示在一个表中。

当我在视图1中单击add user时,我被重定向到视图2。

视图2 ->有两个输入字段和一个按钮(用于添加新用户)。

当我重定向到视图1时,我希望添加新用户,但这不起作用

为了方便起见,我在这里演示了这个- http://plnkr.co/edit/yz6mpplZGh4q5bPDO2bc?p=preview

您总是覆盖列表控制器条目上的'users'内容。

将控制器更改为

    ...
controller('UserController', function($scope,UserService){
if (!$scope.users)
{
  UserService.getUsers().then(function(data){
    $scope.users = data;
  })            
}
    ...

把你的"正确"带回来

 $scope.users.push($scope.user)

View2指令需要定义它需要View1。这将告诉Angular把View1的控制器作为参数传递给View2的控制器。

你可以在控制器上调用addUser(..)方法。

https://docs.angularjs.org/guide/directive creating-directives-that-communicate