ng-repeat中的Angular指令,$ http.get在过滤器上重新运行

时间:2017-03-17 05:58:25

标签: angularjs angularjs-ng-repeat directive

在指令上使用ng-repeat显示来自客户对象数组的客户照片集合。该指令获取客户ID并向返回图像数据的api发出$ http.get请求。我还有一个搜索输入来过滤显示的客户对象。每当我开始清除搜索输入并且更多项返回到视图时,angular再次为指令的每个实例生成$ http.get请求并重新下载图像数据。我该如何避免这种情况?谢谢!

HTML:

  <div class="row">
        <div class="col-lg-12">
            <contact-photo ng-repeat="customer in customers.customerList | filter:customers.search" id="customer.id" />
        </div>
  </div>

控制器:

function Customers($http) {
    var vm = this;

    $http.get('/api/customers')
       .then(function (response) {
           vm.customerList = response.data;
       });
};

指令:

function contactPhoto() {
    return {
        scope: {},
        bindToController: {
            id: '='
        },
        templateUrl: 'app/common/contactPhoto.vbhtml',
        controller: function ($http, $scope) {
            var vm = this;

            //vm.imgSrc
            $scope.$watch('vm.id', function (newval, oldval) {
                if (newval) {
                    $http.get('/api/Customers/' + vm.id + '/photo?shape=square')
                        .then(function (response) {
                            if (response.data != null) {
                                vm.imgSrc = 'data:image/jpeg;base64,' + response.data;
                            } else {
                                vm.imgSrc = "content/img/DefaultUser.png"
                            }
                        });
                }
            });
        },
        controllerAs: 'vm'
    };
}

更新1:

我更改了我的指令控制器以删除有问题变量的$ watch。我仍然遇到同样的问题,它会在每个过滤器上重新运行。

function contactPhoto() {
    return {
        scope: {},
        bindToController: {
            id: '='
        },
        templateUrl: 'app/common/contactPhoto.vbhtml',
        controller: function ($http, $scope, $timeout) {
            var vm = this;

            //vm.imgSrc
            $timeout(function () {
                $http.get('/api/Customers/' + vm.id + '/photo?shape=square')
                    .then(function (response) {
                        if (response.data != null) {
                            vm.imgSrc = 'data:image/jpeg;base64,' + response.data;
                        } else {
                            vm.imgSrc = "content/img/DefaultUser.png"
                        }
                });
            })
        },
        controllerAs: 'vm'
    };
}

0 个答案:

没有答案