Angular指令:重新缩放图像,在ngSrc更改时更新

Angular directive: rescale images, update when ngSrc changes

本文关键字:ngSrc 更新 图像 指令 新缩放 缩放 Angular      更新时间:2023-09-26

我有一个Angular指令,它当前在触发加载事件时执行任务:

.directive("testDir", [
    function() {
        return {
            link: function(scope, elm, attrs) {
                    ...
                return elm.one("load", function() {
                    return ...
                });
            }
        };
    }
]);

该指令被添加到来源于ng-src<img>标记中。该指令旨在缩小图像的大小,以在移动设备上实现更好的性能。

现在我的问题是:我希望指令函数不是在.one()时间触发的,而是在每次触发后,ng-src的链接变量(通过{{}})确实发生了变化。我怎么能意识到这一点?

我希望指令尽可能独立,所以我希望它中没有底层控制器的显式变量名。

JavaScript:

.directive(
  "testDir", [
    function() {
      return {
        scope: {
          imgSrc: '='
        },
        link: function(scope, elm, attrs) {
          scope.$watch(
            'imgSrc', function(newVal) {
              // here you can update whatever you want
            }
          );
        }
      };
    }
  ]
);

HTML:

<img ng-src="{{scopeModel}}" test-dir img-src="scopeModel"/>

编辑2

好吧,这是用画布而不是css。你应该明白这个想法。我把它作为一个完整的元素指令,因为我使用了两个参数-百分比和url:

script.js

var myApp = angular.module('myApp', []);
myApp.controller("MyCtrl", function($scope) {
  $scope.i = 0;
  $scope.urls = ["_71832498_71825880.jpg",
    "0411_hubble_970-630x420.jpg"
  ]
  $scope.changePic = function() {
    if ($scope.i == 0) {
      $scope.i = 1;
      return;
    }
    if ($scope.i == 1) {
      $scope.i = 0;
      return;
    }
  }
})
myApp.directive("scaleImage", [
  '$http',
  function($http) {
    return {
      restrict: 'E',
      scope: {
        percent: '&',
        url: '&',
      },
      template: '<img ng-src="{{ src }}" />',
      link: function (scope, elm, attrs) {
        var img;
        scope.$watch(function () {
          // Because we're returning an object we need to deep watch.  Do this sparingly.
          // Doing this on large arrays or objects can be ill-performant, but I think this
          // is fine here.
          return {
            percent: scope.percent(),
            url: scope.url(),
          }
        }, function (value) {
          if (!value.percent || !value.url) {
            return;
          }
          // Remove the old one, if any.  Should hopefully fix any memory leaks related to
          // creating an element.
          if (img) {
              img.remove();
          }
          img = angular.element('<img style="display: none" src="' + value.url + '">');
          elm.append(img);
          // This will give it enough time to load the image and render the element 
          // so that it has a height and whatnot; may not be needed.  Was needed in plunker
          // at some point; can't tell on localhost, doesn't seem to hurt.
          $http.get(value.url).then(function () {
            var canvas, ctx, neededHeight, neededWidth;
            neededHeight = img[0].naturalHeight * value.percent / 100;
            neededWidth = img[0].naturalWidth * value.percent / 100;
            canvas = document.createElement("canvas");
            canvas.width = neededWidth;
            canvas.height = neededHeight;
            ctx = canvas.getContext("2d");
            ctx.drawImage(img[0], 0, 0, neededWidth, neededHeight);
            scope.src = canvas.toDataURL("image/jpeg");
          });
        }, true); // true to deep watch
      }
    };
  }
]);

index.html

<!DOCTYPE html>
<html>
<head>
  <script src="angular.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <div ng-app="myApp" ng-controller="MyCtrl">
    <input type="number" ng-model="percent" ng-init="percent = 4">
    <scale-image url="urls[i]" percent="percent"></scale-image>
    <button ng-click="changePic()">Change Picture</button>
  </div>
</body>
</html>

编辑

http://plnkr.co/edit/MoEsJPRwR1nFOhRKd37q?p=preview

myApp.directive("scaleImage", [
  function() {
    return {
      link: function(scope, elm, attrs) {
        attrs.$observe('scaleImage', function (value) {
          elm.css('width', value + '%');
          elm.css('height', value + '%');
        });
      }
    };
  }
]);

如果这不起作用,请告诉我。


你能做到吗:

attrs.$observe('src' /* might be `ngSrc` */, function (value) { /* this is executed when the interpolated value of src changes */ });

如果这不起作用,你能设置一个plunker或fiddle吗?