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

时间:2014-09-15 01:02:19

标签: javascript angularjs angularjs-directive html5-canvas

我有一个Angular指令,它当前在触发load事件时完成它的工作:

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

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

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

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

2 个答案:

答案 0 :(得分:2)

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"/>

答案 1 :(得分:1)

编辑2

好吧,这是用canvas而不是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或小提琴吗?