3

当有人选择它作为输入时,我试图显示一张照片。现在我可能过于简单化了 angularjs,但我希望这段代码能够工作。

    <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

我的angularjs文件如下

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

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

clientDashboard.controller('imgCtrl',imgCtrl);

不幸的是,什么都没有发生,我看不到我更新的图像。我真的需要为此编写样板代码吗?

4

1 回答 1

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

于 2013-10-17T23:36:13.080 回答