当数据发生变化时,Angular ng-if指令会持续消耗更多内存

时间:2014-07-07 16:22:31

标签: javascript angularjs

我遇到了一个我一直在工作的Angular应用程序的问题。它显示数据行,并在每列中使用ng-if指令来控制前缀和其他描述性文本或图像。

它运行良好,除了内存使用量持续增长并且相当快,具体取决于我显示的数据量以及更改的速度。

我写了一篇证明这个问题的插件。我在Chrome开发工具中使用timeline memory view来查看内存使用情况。如果取出ng-if指令,每个GC后内存将恢复正常。

http://plnkr.co/edit/Wcl9eJWy1AXqcNr8rpf1

HTML:

<body ng-app="MyApp">
<div ng-controller="RepoCtrl">
    <div class="row">
        <div class="col-md-12">
            <table class="table table-condensed table-striped table-bordered table-responsive">
                <tr>
                    <th>Repo</th>
                    <th>Owner</th>
                    <th>Git URL</th>
                    <th>Description</th>
                </tr>
                <tr ng-repeat="repo in repos">
                    <td>
                        <p ng-if="repo.name">{{ repo.name }}</p>
                    <td>
                        <p ng-if="repo.owner.login">{{ repo.owner.login }}</p>
                    </td>
                    <td>
                        <p ng-if="repo.git_url">{{ repo.git_url }}</p>
                    </td>
                    <td>
                        <p ng-if="repo.description">{{ repo.description }}</p>
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>

JavaScript的:

<script type="application/javascript">
    var app = angular.module("MyApp", ['ngResource']);

    app.factory('RepoFactory', ['$resource', function ($resource) {
        console.log('updated data');
        return $resource(':user.json', {}, {
            query: { method: 'GET', params: {}, isArray: true }
        });
    }]);

    app.controller("RepoCtrl", ['$scope', '$http', '$interval', 'RepoFactory', function ($scope, $http, $interval, RepoFactory) {
        function poll() {
            if (typeof $scope.last === 'undefined') {
                $scope.last = 'vye';
                console.log('no previous query, using vye')
            } else if ($scope.last == 'vye') {
                $scope.last = 'angular';
                console.log('got repos for vye last time, using angular')
            } else if ($scope.last == 'angular') {
                $scope.last = 'vye';
                console.log('got repos for angular last time, using vye')
            }
            RepoFactory.query({user: $scope.last}, function(data){
                $scope.repos = data;
            });
        }

        var promise = $interval(poll, 5000);

        $scope.$on('$destroy', function () {
            if (angular.isDefined(promise)) {
                $interval.cancel(promise);
                promise = undefined;
            }
        });
    }]);

</script>

由于我的疏忽,这是一个错误还是预期的行为?

1 个答案:

答案 0 :(得分:1)

这是AngularJS的一个错误,已在最新版本(1.3.0-beta.14)中修复。

https://github.com/angular/angular.js/issues/8105

相关问题