javascript - 将一些代码从 jQuery 重写为 Angular

标签 javascript jquery angularjs

我刚刚学习,现在正在将我的代码从 jQuery 重写为 Angular,遇到一些问题,希望你能帮我解决这些问题。

当前 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');
    })
};

那么,到底如何在 Angular 中查看这段代码呢? 我目前的尝试:

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

我想我必须在 html 中添加类似 ng-src 的内容...任何帮助将不胜感激。

最佳答案

您需要将返回的图像 src 添加为 $scope 上的属性以在模板中引用,然后按照您所说的使用 ng-src 。希望这将作为一个起点;

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

关于javascript - 将一些代码从 jQuery 重写为 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908157/

相关文章:

javascript - 选择 RadioButton 的值

javascript - Mootools 相当于 $.each

javascript - 函数不是函数 jquery

javascript - 如何在指令中访问子 Controller 和父 Controller ?

php - Angularjs $http.post,将数组传递给 PHP

javascript - 如何通过单击图像打开文本?

javascript - 取消初始化数据表(从内存中清除)?

javascript - Ajax 选项卡设置不适用于本地主机 (EasyTabs)

javascript - 当涉及到 "this"选择器时,jQuery 的层次结构是如何工作的?

javascript - Angular 图书应用程序示例的两种方式绑定(bind)问题