即使我更改了图像,图像也没有改变 [英] Image is not changing even i changed image

查看:64
本文介绍了即使我更改了图像,图像也没有改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在angularjs中,如果我更改或删除图像,则不会进行任何更改.刷新页面后,它会显示更改后的图像.我正在使用以下行来删除图像

In angularjs if i change or remove image it does not make any changes. After refreshing the page it show the changed image.I am using following line to remove image

jQuery

$('#profile_image').val('')

推荐答案

如果要在AngularJS中操作DOM,则应使用

If you want to manipulate the DOM in AngularJS you should use directives for this purpose.

您应该避免在控制器内部使用jquery,而只需使用模型即可.以下是fileUpload指令,它可以帮助您以更角度的方式使用<input type="file">:

You should avoid using jquery inside of your controllers and simply work with your model. Below is fileUpload directive that could help you to work with <input type="file"> in a more angularjs-way:

angular.module('myApp', [])
.controller('TestController', ['$scope', function ($scope) {
    var ctrl = this;
    
    ctrl.imageFile = null;
    ctrl.clearFile = clearFile;
    
    function clearFile(){
      ctrl.imageFile = null;
    }
    
    $scope.$ctrl = ctrl;
}])
.directive('fileUpload', [function () {
  return {
    require: "ngModel",
    restrict: 'A',
    link: function ($scope, el, attrs, ngModel) {
      function onChange (event) {
        //update bindings with $applyAsync
        $scope.$applyAsync(function(){
          ngModel.$setViewValue(event.target.files[0]);
        });
      }
      //change event handler
      el.on('change', onChange);
      
      //set up a $watch for the ngModel.$viewValue
      $scope.$watch(function () {
        return ngModel.$viewValue;
      }, function (value) {
        //clear input value if model was cleared
        if (!value) {
          el.val("");
        }
      });
      //remove change event handler on $destroy
      $scope.$on('$destroy', function(){
        el.off('change', onChange);
      });
    }
  };
}]);

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.angularjs.org/1.3.20/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="TestController">
    <input type="file" file-upload ng-model="$ctrl.imageFile" />
    <input type="button" ng-click="$ctrl.clearFile()" value="Reset" />
    <div ng-if="$ctrl.imageFile">
      {{$ctrl.imageFile.name}}<br />
      {{$ctrl.imageFile.size}} byte(s)<br/>
      {{$ctrl.imageFile.type}}
    </div>
  </div>
</div>

更新:另请参见 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆