Angularjs-ng repeat不反映属性数组中的更改

Angularjs - ng-repeat does not reflect changes in property array

本文关键字:数组 属性 repeat Angularjs-ng      更新时间:2023-09-26

我的HTML有一个带有ng repeat:的循环

<div class="row">
    <div ng-repeat="item in model.painel track by item.codigoIncidente">
            <strong>{{item.restante.horaMinutoSegundo}}</strong>
    </div>
</div>

我的控制器有一个$interval,它递减horaMinutoSegundo。

nihilApp.controller('IncidentePainelController', ['$scope', '$interval', 'Incidente', function ($scope, $interval, Incidente) {
    $scope.model = {
        painel: [],
    };
    var find = function() {
        Incidente.listPainel({pagina: 0}).$promise.then(function (result) {
            $scope.model.painel = result.pagedList;
            $scope.model.totalItems = result.totalGeral;
        }, function (error) {
            console.log(error);
        });
    };
    var updateTime = function() {
        for (var i = 0; i < $scope.model.painel.length; i++) {
        if ($scope.model.painel[i].status.id === 'E' && $scope.model.painel[i].restante.segundos > 0) {
            var segundos = $scope.model.painel[i].restante.segundos - 1;
            $scope.model.painel[i].restante.horaMinutoSegundo = getHoraMinutoSegundo(segundos);
        }    
        }

    };

    var getHoraMinutoSegundo = function (segundos) {
        var horaMath = Math.floor(segundos / 3600);
        var remMath = Math.floor(segundos % 3600);
        var minutoMath = Math.floor(remMath / 60);
        var segundoMath = Math.floor(remMath % 60);
        var hrStr = (horaMath < 10 ? "0" : "") + horaMath;
        var mnStr = (minutoMath < 10 ? "0" : "") + minutoMath;
        var secStr = (segundoMath < 10 ? "0" : "") + segundoMath;
        return hrStr.concat(":").concat(mnStr).concat(":").concat(secStr);
    };    
    $interval(updateTime, 1000);
    find();
}]);

但是{{item.restante.horaMinutoSegundo}}不会在HTML中更新。有人能帮我解决这个问题吗?非常感谢!

https://jsfiddle.net/araraujo/96w3jrrh/

它应该可以工作,但您的代码中有一个小错误。

var segundos = $scope.model.painel[i].restante.segundos - 1;

您将新的segundos值放入变量中,但没有更新作用域中的值。

这是更新版本的小提琴

有两件事你需要改变

  1. 在控制器中注入$interval

    app.controller('MainCtrl',函数($scope,$interval){}

  2. 更新您的模型,使其与for循环中的逻辑匹配。下面是这样的。

    $scope.model={painel:〔{restante:1}〕}

必须在末尾添加$scope.apply。

var updateTime = function() {
    for (var i = 0; i < $scope.model.painel.length; i++) {
    if ($scope.model.painel[i].status.id === 'E' && $scope.model.painel[i].restante.segundos > 0) {
        var segundos = $scope.model.painel[i].restante.segundos - 1;
        $scope.model.painel[i].restante.horaMinutoSegundo = getHoraMinutoSegundo(segundos);
    }    
    }
$scope.apply();
};

发现缺口,更换此线

var segundos = $scope.model.painel[i].restante.segundos - 1;

scope.model.painel[i].restante.segundos = $scope.model.painel[i].restante.segundos - 1;