如果模型开始为空,如何处理 ngRepeat 模型中的新项目

How to handle new items in ngRepeat model if model starts empty

我有一个项目列表 (list1),它将通过 ng-repeat 显示在浏览器中。 通过从其他列表 (list2) 中选择项目,可以将这些项目添加到 list1。

我写了一个方法来将项目添加到模型中。如果 list1 不为空,这很有效。但是如果 list1 为空,item 将添加到模型但没有 ng-repeat 来处理它。 源代码仅包含 HTML-注释:

<!-- ngRepeat: item in list1 -->

我应该在我的代码中添加什么才能让这个 ngRepeat 处理新项目?

问候 托马斯

这里有一个 jsfiddle 演示您要执行的操作,请尝试单击 List2 中的项目,它会将其添加到 List1。 我们有两个列表 HTML:

<h3>List1</h3>
<ul>
  <li ng-repeat="person in list1">{{person.name}}</li>
</ul>
<h3>List2</h3>
<ul>
    <li ng-repeat="person in list2" ng-click="ToList1(person)">{{person.name}}</li>
</ul>

并且在我们的控制器中,必须定义我们的list1模型,所以当我们向它推送数据时,

$scope.persons = [{name:"john"},{name:"mouhamed"},{name:"emilie"}];
// Initialise list1 as an empty array
$scope.list1 = [];
$scope.list2 = $scope.persons;

$scope.ToList1 = function(person){
  $scope.list1.push(person);  
};

ToList1 函数在单击 List2 中的一项时触发,它将对象(在您的示例中)添加到 list1 模型。


如果你为每个列表使用一个控制器,你可以使用 $rootScope.$emit()$rootScope.$on() 在控制器之间进行通信的功能。

function FirstCtrl($scope, $rootScope) {

  $scope.list1 = [];
  // Listener for the list1/add event, that will execute the callback when received a 'list1/add' event
  $rootScope.$on('list1/add', function (event, data) {
    $scope.list1.push(data);
  });
}

function SecondCtrl($scope, $rootScope) {
   $scope.persons = [{
    name: "john"
   }, {
    name: "mouhamed"
   }, {
    name: "emilie"
   }];
  $scope.list2 = $scope.persons;

  $scope.ToList1 = function (person) {
    // Emit the 'list1/add' event with the selected person object
    $rootScope.$emit('list1/add', person);
  };
}

这里有一个 JSFiddle 来演示这种情况。