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

时间:2017-06-10 06:47:15

标签: javascript

我正在使用聊天应用。在这里,我必须以用户可以编辑其个人资料图片的方式为用户的个人资料图片写一个code

  

如何在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>

2 个答案:

答案 0 :(得分:0)

使用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

// 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);
        }
    }
}

答案 1 :(得分:0)

您可以为图片添加ng-src属性,并为onchange撰写input方法。

<强> 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:

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]);
  }
});

这是工作jsfiddle