计算ng-repeat中宽度图像的总和

时间:2014-08-20 03:29:02

标签: image angularjs angularjs-directive angularjs-ng-repeat

我想计算ng-repeat中所有图像的宽度总和。

<span ng-repeat="result in input.results">
            <img 
              ng-src="{{pathImage}}/{{result.small}}" 
              imagesize/>
    </span>
<p> The size is : {{totalWidth}}</p>

我制作一个知道宽度的指令imageize

app.directive('imagesize', function(){ 
   return {
     restrict: 'A',
     link: function(scope, elem, attr) {
         elem.on('load', function() {
            var w = $(this).width(),
                h = $(this).height();

         });
     }
   };
});

但我不知道如何将这笔总和加入总宽度。

1 个答案:

答案 0 :(得分:2)

模板

<span ng-repeat="result in input.results">
            <img 
              ng-src="{{pathImage}}/{{result.small}}" 
              imagesize images-properties="imagesProperties"/>
    </span>
<p> The size is : {{imagesProperties.totalWidth}}</p>

指令

app.directive('imagesize', function(){ 
   return {
     restrict: 'A',
     scope: {
       imagesProperties: '='
      },
     link: function(scope, elem, attr) {
         elem.on('load', function() {
            var w = $(this).width(),
                h = $(this).height();
            scope.imagesProperties.totalWidth += w;
         });
     }
   };
});

在Controller中初始化imagesProperties.totalWidth

app.controller('ImageCtrl', function($scope){
    $scope.imagesProperties = {
        totalWidth = 0
    };
...
});