问题
My plan is to create a QR code by using an API (such as Google Charts API) and then show the generated QR code on my website. I created a function that requests a QR Code image from Google Chart API:
.controller('DealCtrl', function($scope, $http) {
$http.get("https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=160%20FSU728F29G&coe=UTF-8")
.success(function(data, status, headers, config) {
$scope.qrcode = data;
}).error(function(data, status, headers, config) {
$scope.qrcode = status;
});
})
When I try to bind the response as HTML, I get this:
<div ng-bind-html="qrcode"></div>
The response seems to be an image (PNG). How can I show this on my website?
回答1:
If you don't want to use the image url as is for some reason and you want to create the image from the contents you can use this:
$http.get(
"https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=160%20FSU728F29G&coe=UTF-8",
{responseType: 'blob'})
.then(function(response) {
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( response.data );
$scope.qrcode = '<img src="'+imageUrl+'"/>';
});
demonstrating jsbin
Credit goes to @jan-miksovsky
回答2:
The returned data seems to be HTML. So you need to inject the Google HTML into your page, using ng-bind-html
directive :
<div ng-bind-html="qrcode"></div>
回答3:
Here is an example of using ng-bind-html http://jsbin.com/lifuparija/edit?html,js,output
But without a more in depth example of what you are trying to accomplish, I feel like this is just a shot in the dark.
回答4:
You can use this directive
and then use it in your html code.
create directive:
angular.module('av.qr', []) .directive('avQr', function() { return { restrict: 'E', template: '', scope: { image: '=' }, link: function(scope, elem, attr) { var qrImage = angular.element(scope.image); elem.append(qrImage); } } })
then in your module inject this directive with module name like below:
angular.module('my.module', ['av.qr'])
In your controller append
QR
image to$scope
as you did:.controller('DealCtrl', function($scope, $http) { $http.get("https://chart.googleapis.com/chart? cht=qr&chs=300x300&chl=160%20FSU728F29G&coe=UTF-8") .success(function(data, status, headers, config) { $scope.qrcode = data; }).error(function(data, status, headers, config) { $scope.qrcode = status; }); })
In your
HTML
code use your directive like this:<av-qr image="qrcode"></av-qr>
** You pass your qrcode
image to your directive.
来源:https://stackoverflow.com/questions/34400499/request-qr-code-and-show-the-image-using-angular-js