impregnable fiend impregnable fiend - 5 months ago 7
Javascript Question

Rewrite some code from jQuery to Angular

I'm just learning, and right now rewrite my code from jQuery to Angular, have some issues, hope you can help me unriddle them.

Current html:

<div class='image_hold'>
<img class='image'>
<input type='hidden' name='image_answer' class='image_input'>
</div>


JS:

function loadGraphic() {
$.post('generate.php', { keyword: 'image' })
.done(function(data) {
$('.image_input').val(data);
$('.image').attr('src', data);
})
.fail(function(data) {
alert('error');
})
};


So, how exactly gonna have to look that bit of code in Angular?
My current attempt:

$scope.loadGraphic = function() {
$http({
method: 'POST',
url: 'generate.php',
data: image,
})
.success(function(data) {
if (data.errors) {
$window.alert(error);
} else {
//
}
});
};


And I suppose I have to add in html something like
ng-src
... Any help will be greatly appreciated.

Answer

You'll want to add the returned image src as a property on $scope to refer to in the template, then use ng-src as you say. Hopefully this will serve as a starting point;

$scope.imageSrc = null;

$scope.loadGraphic = function() {
    $http({
        method:  'POST',
        url:     'generate.php',
        data:    image,
    })
    .then(function(data) {
        $scope.imageSrc = data;
    })
    .catch(function(errorResponse) {
        // Handle errors in here
    });
};

// Template
<!-- ... -->
<img ng-if="imageSrc" ng-src="imageSrc" class="image">