나는 같은 이미지가 있습니다 <img ng-src="dynamically inserted url"/>. 단일 이미지를로드 할 때 이미지를 스크롤 할 수 있도록 iScroll refresh () 메서드를 적용해야합니다.
콜백을 실행하기 위해 이미지가 완전히로드 된시기를 아는 가장 좋은 방법은 무엇입니까?
답변
다음은 이미지 onload http://jsfiddle.net/2CsfZ/2/ 를 호출하는 방법의 예입니다.
기본 아이디어는 지시문을 만들고 img 태그에 속성으로 추가하는 것입니다.
JS :
app.directive('imageonload', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                alert('image is loaded');
            });
            element.bind('error', function(){
                alert('image could not be loaded');
            });
        }
    };
});HTML :
 <img ng-src="{{src}}" imageonload />답변
사용자 지정 $scope메서드를 호출 할 수 있도록 약간 수정했습니다 .
<img ng-src="{{src}}" imageonload="doThis()" />지침 :
.directive('imageonload', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element.bind('load', function() {
                    //call the function that was passed
                    scope.$apply(attrs.imageonload);
                });
            }
        };
    })누군가가 매우 유용하다고 생각하기를 바랍니다. 감사합니다 @mikach
그러면 doThis()함수는 $ scope 메서드가됩니다.
답변
@ Oleg Tikhonov : 방금 이전 코드를 업데이트했습니다 .. @ mikach 감사합니다 ..)
app.directive('imageonload', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        element.bind('load', function() {
            alert('image is loaded');
        });
        element.bind('error', function(){
             alert('image could not be loaded');
        });
    }
  };
});답변
내 대답 :
 var img = new Image();
 var imgUrl = "path_to_image.jpg";
 img.src = imgUrl;
 img.onload = function () {
      $scope.pic = img.src;
 }답변
방금 이전 코드를 업데이트했습니다 ..
<img ng-src="{{urlImg}}" imageonload="myOnLoadImagenFunction">그리고 지시 …
    .directive('imageonload', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element.bind('load', function() {
                    scope.$apply(attrs.imageonload)(true);
                });
                element.bind('error', function(){
                  scope.$apply(attrs.imageonload)(false);
                });
            }
        };
    })답변
기본적으로 이것은 내가 사용한 솔루션입니다.
$ apply ()는 적절한 상황에서 외부 소스에 의해서만 사용되어야합니다.
적용을 사용하는 대신 호출 스택의 끝까지 범위 업데이트를 던졌습니다. “scope. $ apply (attrs.imageonload) (true);”만큼 잘 작동합니다.
window.app.directive("onImageload", ["$timeout", function($timeout) {
    function timeOut(value, scope) {
        $timeout(function() {
            scope.imageLoaded = value;
        });
    }
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            element.bind('load', function() {
                timeOut(true, scope);
            }).bind('error', function() {
                timeOut(false, scope);
            });
        }
    };
}]);답변
