its*_*sme 18 javascript image angularjs
是否有可能通过给定的URL检查图像是否存在并且它是图像资源?
例如:
angular.isImage('http://asd.com/asd/asd.jpg')
Run Code Online (Sandbox Code Playgroud)
或者它只是服务器端的东西?
没有意思,请不要使用它
dfs*_*fsq 46
我认为最好的javascript方法是将HTMLImageElement对象与延迟对象一起使用:
function isImage(src) {
var deferred = $q.defer();
var image = new Image();
image.onerror = function() {
deferred.resolve(false);
};
image.onload = function() {
deferred.resolve(true);
};
image.src = src;
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
用法:
isImage('http://asd.com/asd/asd.jpg').then(function(test) {
console.log(test);
});
Run Code Online (Sandbox Code Playgroud)
使用HTMLImageElement会带来一些好处:不仅可以测试文件是否可下载,还可以通过img标记显示有效的图像资源.
我把这个代码包装在简单的服务中进行测试,它似乎工作:
app.controller('MainCtrl', function($scope, Utils) {
$scope.test = function() {
Utils.isImage($scope.source).then(function(result) {
$scope.result = result;
});
};
});
app.factory('Utils', function($q) {
return {
isImage: function(src) {
// ... above code for isImage function
}
};
});
Run Code Online (Sandbox Code Playgroud)
你可以使用ng-src
<img ng-src="" />
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用http模块检查它是否存在.
var app = angular.module('myapp', []).run(function($http){
$http.get('http://asd.com/asd/asd.jpg',
//success
function(data){
};
});
Run Code Online (Sandbox Code Playgroud)
更新:
HTML
<div ng-controller="Ctrl">
<img ng-src="{{src}}" isImage />
</div>
Run Code Online (Sandbox Code Playgroud)
JS
var app = angular.module('app', []);
app.directive('isImage', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('load', function() {
alert('image is loaded');
});
}
};
});
app.controller('Ctrl', function($scope) {
$scope.src ="http://asd.com/asd/asd.jpg";
});
Run Code Online (Sandbox Code Playgroud)