3

I'm trying to show a photo when someone selects it for an input. Now I might be over simplyfying angularjs too much but I was hoping that this code would work.

    <div ng-app="app">

    ... html stuff ...

    <div ng-controller="imgCtrl">

    <input ng-model="imageSource" type="file"></input>   
    <img ng-src="{|imageSource|}"></img>

    </div>

    </div> end of app

Where my angularjs file is as follows

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

var imgCtrl = function ($scope,$http){
    $scope.wall = _wall;
};

clientDashboard.controller('imgCtrl',imgCtrl);

Unfortunately, nothing is happening and I can't see my updated image. Do I really have to write boiler plate code for this?

Dr.Knowitall
  • 10,080
  • 23
  • 82
  • 133

1 Answers1

2

I got it working in chrome and firefox but my quick research shows that it is a security risk and may not even be allowed eventually. See here: http://jsfiddle.net/28ZJw/

HTML:

<div ng-app="app">
  <div ng-controller="imgCtrl">
    <input ng-model="imageSource" type="file" onchange="angular.element(this).scope().fileNameChaged(this)"></input>
    <img ng-src="{|imageSource|}"></img>
  </div>
</div>

JS:

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

app.controller('imgCtrl', function($scope, $http)
{
    $scope.imageSource = "";
    $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]);
    }
});

The right way would be to get this going with ng-change however I couldn't get it to work. I am not sure if ng-change applies to file input fields

Ronnie
  • 11,138
  • 21
  • 78
  • 140
  • Ya I tried doing it with ng-change as well. Technically you're suppose to 'invent' your own directive to handle this. Unfortunately that takes time and effort that I don't even want to deal with, considering I've been working on this project long enough and just started learning Angular. Thanks for the help! – Dr.Knowitall Oct 17 '13 at 23:51
  • yeah I would turn it into a directive for sure. I just started making little widgets using directives yesterday so I am not confident enough to make that a directive yet. I'm new too – Ronnie Oct 17 '13 at 23:55
  • 2
    here's a directive that might be useful http://stackoverflow.com/questions/17063000/ng-model-for-input-type-file – jaime Oct 18 '13 at 00:01
  • 1
    there ya go, that is slick – Ronnie Oct 18 '13 at 00:03