如何使用Angular Js在Div中显示图像 [英] How to display Image in Div using Angular Js

查看:79
本文介绍了如何使用Angular Js在Div中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码可以正常工作以在Img标签中显示图像

This code is working fine To display Image in Img Tag

$scope.isImage = function(ext) {
  if(ext) {
    return ext == "jpg" || ext == "jpeg"|| ext == "gif" || ext=="png"
  }
}

此处正在演示 http://plnkr.co/edit/rAZVSFRURCkgxQrZAtvO?p=preview

我想在

<div style="background-image:url(How can i get browsed image file)"></div>

推荐答案

您需要在DOM中创建一个路径字符串来表示您浏览的文件,然后将其添加为背景图像url.我通过修改您的代码来使其正常工作.

You need to create a path string in DOM to represent your browsed file and then add it as background image url. I got it working by modifying your code like below.

<body>
    <form action="" id="contactproForm" method="post" ng-app="myApp" ng-controller="myCtrl" enctype="multipart/form-data">

        <label for="file">Attachment</label>
        <div class="input-box">
          <input type="file" id="file" class="input-text" ngf-change="onChange(picFile)" ngf-select ng-model="picFile" name="attachement" accept="image/png, image/jpeg, image/jpg, application/msword, application/vnd.ms-excel, application/pdf " />
        </div>
        <div id="image"class="image" style="width:200px;height:200px;background-image:url('');"></div>       <!-- div with id="image"-->

    </form>


    <script>
    var app = angular.module('myApp', ['ngFileUpload']);

    app.controller('myCtrl', ['$scope', '$http', '$timeout', '$compile', 'Upload',
        function($scope, $http, $timeout, $compile, Upload) {
            $scope.onChange = function(files) {
                if (files[0] == undefined) return;
                if($scope.isImage(files[0].name.split(".").pop())){  // checking if image
                    var path = URL.createObjectURL(files[0]);       //  creating a path for file
                    document.getElementById('image').style.backgroundImage = "url(" + path + ")";   // setting it as background image of div
                }else{
                    alert("not Image");
                }
            }

            $scope.isImage = function(ext) {
                if (ext) {
                    return ext == "jpg" || ext == "jpeg" || ext == "gif" || ext == "png"
                }
            }
        }
    ]);
    </script>

</body>

我已添加了有关所做更改的评论.

I've added comments for changes made.

这篇关于如何使用Angular Js在Div中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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