如何从另一个控制器更新控制器的ng-repeat模型?

时间:2015-03-06 18:18:50

标签: javascript angularjs angularjs-scope angularjs-ng-repeat angular-digest

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

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()并在$scope.listEntries中设置serviceForFirst值。然后我使用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
};
});

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

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>

但是第一个<div>中的列表没有更新。如果我在设置$scope.$apply()之前尝试在getList()中执行$scope.listEntries,那么我的$ digest已经在进行中。

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

我应该如何更新清单?

1 个答案:

答案 0 :(得分:6)

您只需要一项服务,该服务包含您打算在不同控制器之间共享的数据。 Demo

模板

<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
    };
});
相关问题