两个控制器,共同的工厂和重复刷新

Two controllers with common factory and ng-repeat refresh

本文关键字:工厂 刷新 两个 控制器      更新时间:2023-09-26

我使用AngularJS有问题。当我从另一个控制器实例

向JSON中添加新项时,Ng-repeat不希望刷新循环

在第一个控制器中设置JSON

(function(){
    'use strict';
    angular.module('mainApp').controller('ListController', function($scope, FavoriteListService) {
    $scope.addToFavorites = function(speaker){
            FavoriteListService.setFavorites(speaker);
        };
})();

在第二个控制器中我必须显示ng-repeat

 (function(){
        'use strict';
        angular.module('mainApp').controller('ShowController', function($scope, FavoriteListService) {
    $scope.favoritesList = FavoriteListService.getFavorites();
  })();
工厂

(function () {
    'use strict';
    angular.module('mainApp').factory('FavoriteListService', function () {
        var obj = {};
        obj.getFavorites = function () {
            var favorites = localStorage.getItem('speaker-favorites');
            if (favorites == null) {
                favorites = {};
            } else {
                favorites = JSON.parse(favorites);
            }
            return favorites;
        };
        obj.setFavorites = function (speaker) {
            var favorites = obj.getFavorites();
                favorites[speaker.uid] = {firstname: speaker.firstname, name: speaker.name};
            localStorage.setItem('speaker-favorites', JSON.stringify(favorites));
        };
        return obj;
    });
})();

模板:

 <ul>
        <li ng-repeat="(key, fav) in favoritesList">
            {{fav.firstname}} {{fav.name}}
        </li>
    </ul>

一切都很好,当设置&显示在一个控制器中。

如果我想使用2个控制器(或1个控制器的2个实例)ng-repeat在加载页面后正确显示所有项目,但当我添加新项目时,它不会刷新循环并且不显示新项目。

有办法修复吗?

您需要将repeater更改为(并将FavoriteListService赋值给$scope变量):

ng-repeat="(key, fav) in FavoriteListService.getFavorites()"

或者$watch在你的控制器中,像这样:

$scope.$watch(
  function() { return FavoriteListService.getFavorites(); },
  function(newValue, oldValue) {
    if ( newValue !== oldValue ) {
      $scope.favoritesList = newValue;
    }
  },
  true
);

因为当你把你的服务方法return赋值给作用域方法时它并没有像引用那样工作。

创建一个空对象,并使用angular.copy来更新对象:

app.factory('FavoriteListService', function () {
    var obj = {};
    //create empty object
    var favorites = {};
    obj.getFavorites = function () {
        let update = localStorage.getItem('speaker-favorites');
        if (update) {
           //Use angular copy
           angular.copy(update, favorites);
        };
        return favorites;
    };
    obj.setFavorites = function (speaker) {
        favorites[speaker.uid] = {firstname: speaker.firstname, name: speaker.name};
        localStorage.setItem('speaker-favorites', JSON.stringify(favorites));
    };
    return obj;
});

通过使用angular.copy,所有使用getFavorites函数的控制器都得到相同的对象引用,并且它们都看到相同的内容变化。

更多信息,参见AngularJS angular。复制API参考