如何从另一个控制器更新控制器的ng重复模型

How to update the ng-repeat model of controller from another controller?

本文关键字:控制器 ng 模型 更新 另一个      更新时间:2023-09-26

我有两个<div>,它们有自己的控制器。第一个div有一个ng-model="listEntries"。我在这个<div>的控制器中初始化listEntries

app.controller('firstController', function($scope,serviceForFirst){
      serviceForFirst.init();
      serviceForFirst.getList($scope);
});

Html

<div ng-controller="firstController">
 <ul>
  <li ng-repeat="each in listEntries">
     {{each.name}}
  </li>
 <ul>
</div>

我将$scope传递给getList(),并在serviceForFirst中设置$scope.listEntries值。然后我使用listEntries作为ng-model

app.service('serviceForFirst',function(){
 var list=[];
 var init=function(){
  list = [{....}];
 };
 var getList=function($scope){
  $scope.listEntries = list;
 };
 var update=function(newEntity){
   list.push(newEntity);
 };
return{
 init:init,
 getList:getList,
 update:update
};
});

这是我的第二个控制器和与之相关的服务。我打算每次调用addNew()时都将新元素推送到listAll中。这就是我努力做到的。

app.controller('secondController', function($scope,serviceForSecond){
  serviceForSecond.init();
  $scope.addNew=function(newEntity){
         serviceForSecond.addNew(newEntity);
  };
});

app.service('serviceForSecond',function(serviceForFirst){
  var entities=[];
 var init=function(){
   entities=[{....}];
 };
 var addNew=function(newEntity){
    entities.push(newEntity);
    serviceForFirst.update(newEntity);
 return{
   init:init,
   addNew:addNew
 };
});

<div> 的HTML

<div ng-controller="secondController">
  ....
  <input type="text" ng-model="newName"/>
  <button ng-click="addNew(newName)"/>
  ....
</div>

但是该列表在第一个CCD_ 14中没有被更新。如果我在设置$scope.listEntries之前尝试在getList()中执行$scope.$apply(),那么我会得到$digest ready in progress错误。

当我执行console.log()时,我看到每个服务中的适当函数都被调用了,但列表没有更新。

我应该如何更新列表?

您只需要一个服务,它保存您打算在不同控制器之间共享的数据。演示

模板

<ul ng-controller='Ctrl1'>
    <li ng-repeat="item in items">
        {{item}}
    </li>
</ul>
<div ng-controller="Ctrl2">
    <input type="text" ng-model="newName"/>
    <button ng-click="addNew(newName)">Add</button>  
</div>

控制器和服务

var app = angular.module('myApp', []);
app.controller('Ctrl1', function($scope, myListService){
    $scope.items = myListService.getList();
});
app.controller('Ctrl2', function($scope, myListService){
    $scope.addNew = myListService.add;
});
app.service('myListService',function(){
    var list=[];
    init();
    function init(){
        list = ['one', 'two', 'three'];
    };
    var getList=function(){
        return list;
    };
    var add=function(newEntity){
        list.push(newEntity);
    };
    return{
        getList: getList,
        add: add
    };
});