简体   繁体   English

如何在单击angularjs中的现有图像时更改配置文件图像?

[英]How can I change the profile image on clicking the existing image in angularjs?

I am working with chat application . 我正在使用聊天应用程序 Here I have to write a code for profile picture of the user in the way that user can edit his profile picture. 在这里,我必须以用户可以编辑他的个人资料图片的方式编写用户个人资料图片的code

How can I implement this code in javascript ? 如何在javascript实现此代码?

  <div class="well"> <h1><img src="user.png" class="img-circle" width="80" height="80" ng-click="imgFn()"> <input type="file" accept="image/*" ng-hide="true" style="font-size:15px"><small>Username</small> </h1> </div> 

Using jquery I did that 使用jquery我做到了

<div class="photo photo-margin">
     <input type="file" onchange="fileChanged()" accept="image/png,image/jpg,image/jpeg">
     <img src="#" class="show-added-photo" id="photoFile"> 
</div>

JS CODE JS代码

// Below function is used to call readURL to add image
function fileChanged() {
    var vals = $(this).val(),
        val = vals.length ? vals.split('\\').pop() : '';
        readURL(this);
};

// Below function to read image URL
function readURL(input) {
    if (input.files && input.files[0]) { // if file are there in page
        var reader      = new FileReader(); // get file reader

        // onload executed on file reader load
        reader.onload   = function(e) {
            $('.show-added-photo').attr('src', e.target.result);
        }
    }
}

You can add ng-src attribute to image and write onchange method for the input . 您可以将ng-src属性添加到image并为input编写onchange方法。

HTML: HTML:

<div ng-app="testApp" ng-controller="testController">
    <div class="well">
        <h1><img src="user.png" class="img-circle" width="80" height="80" ng-click="imgFn()" ng-src="{|imageSource|}">
            <input type="file" accept="image/*" ng-model="imageSrc" onchange="angular.element(this).scope().fileNameChaged(this)" style="font-size:15px">
            <small>Username</small>
        </h1>
    </div>
</div>

Javascript: 使用Javascript:

var app = angular.module('testApp', []).config(function($interpolateProvider) {
  $interpolateProvider.startSymbol('{|');
  $interpolateProvider.endSymbol('|}');
});

app.controller('testController', function($scope){
  $scope.imageSrc = ""
  $scope.fileNameChaged = function(element) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $scope.$apply(function() {
        $scope.imageSource = e.target.result;
      });
    }
    reader.readAsDataURL(element.files[0]);
  }
});

And here is the working jsfiddle 这是工作的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM