将图像添加到AngularJS中的列表项

时间:2016-09-27 16:50:38

标签: javascript angularjs mongodb

我有一个简单的购物清单,需要能够将图像上传到单个列表项。使用MongoDB和AngularJS。

图像应绑定到$ scope.list.items,因此将图像添加到列表项(例如面包图片)。如何上传图像并将其作为该对象的一部分绑定?基本上,一旦完成,项目列表也将包含图像。

用于显示项目的HTML:

<ul class="list-group">
            <li style="color:{{list.color}}" class="list-group-item" ng-repeat="item in list.items | orderBy:propertyName:reverse | filter: search ">
                <input type="checkbox" ng-model="item.isChecked" ng-click="editItem()">
                {{item.name}} - {{item.priority}}
                <i class="fa fa-trash-o" aria-hidden="true" ng-click="removeItem(item)"></i>&nbsp

                <i class="fa fa-pencil" aria-hidden="true" href ng-click="showEdit = !showEdit" ng-show="!showEdit"></i><br>
                <small class="form-text text-muted">Note: {{item.note}}</small>
                <div ng-show = "showEdit"> 
                    <h4>Edit {{item.name}}</h4>
                    <form ng-submit="editItem()">
                        <input class="form-control" type="text" name="name" id="name" ng-model="item.name" maxlength="25" required>
                        <select class="form-control" name="priority" id="priority" ng-model="item.priority" required>
                            <option value="">Priority</option>
                            <option value="High">High</option>
                            <option value="Low">Low</option>
                        </select>
                        <input type="text" class="form-control" name="note" id="note" ng-model="item.note" maxlength="255" value= " ">
                        <button class="btn btn-default" type="submit" ng-click="showEdit = !showEdit">Update</button>
                    </form>
                </div>
                <br>

            </li> 
        </ul>

以下是添加项目的HTML:

<button class="btn btn-default btn-custom" href ng-click="showAddItem = !showAddItem" ng-show="!showAddItem">Add Item</button>
        <div ng-show="showAddItem" class="add-item">
            <h4>Add Item</h4>
            <form ng-submit="addItem()">
                <input class="form-control" type="text" name="name" id="name" ng-model="newItem.name" placeholder="Item" maxlength="25" required>
                <select class="form-control" name="priority" id="priority" ng-model="newItem.priority" required>
                    <option value="">Priority</option>
                    <option value="High">High</option>
                    <option value="Low">Low</option>
                </select>
                <input type="text" class="form-control" name="note" id="note" ng-model="newItem.note" placeholder="Note" maxlength="255" value= " ">

                <button class="btn btn-default btn-add" type="submit">Add</button>&nbsp<span class="close-box" ng-click="showAddItem = !showAddItem"><u>close</u></span>    
            </form>
             <!-- <button class="btn btn-default btn-lg btn-custom" href="">Add Item</button> -->
        </div><br><br>
        <a ng-href="#/home"><button class="btn btn-default btn-lg btn-home">Save & Return</button></a>

    </div>

用于添加项目的控制器:

(function () {
'use strict';

var app = angular.module('myApp');

app.controller('ShoppingListController', ['$scope', '$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, $routeParams, API_BASE, $location){


    // GET SPECIFIC LIST
    $scope.list = [];
    var id = $routeParams.id;

    $http({
        method: 'GET',
        url: API_BASE + 'shopping-lists/' + id
    }).then(function successCallback(response) {
        $scope.list = response.data[0];
    }, function errorCallback(response) {
        console.log('it did not work');
        console.log(response.statusText);
    });


    // REMOVE LIST
    $scope.removeList = function(){
        var id = $scope.list.id;
        console.log(id);
        $http.delete(API_BASE + 'shopping-lists/' + id)
            .success(function (data, status, headers, config) {
                console.log('you deleted :' + $scope.list);
            })
            .error(function (data, status, header, config) {
            });
        $location.path('/home');    
    };

    // RANDOM ID
    function makeid()
    {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        for( var i=0; i < 20; i++ ){
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }

        text += Date.now();

        return text;
    }


    // ADD ITEM
    $scope.addItem = function(){
        var created = new Date();
        var newID = makeid();

        if($scope.list.hasOwnProperty('items') === false){
            $scope.list.items = [];
        }
        $scope.list.items.push({
            name : $scope.newItem.name,
            priority : $scope.newItem.priority,
            note: $scope.newItem.note,
            isChecked: false,
            listId: $scope.list.id,
            created: created,
            id: newID
        });
        // console.log($scope.list.items);
        $http.put(API_BASE + 'shopping-lists/', $scope.list)
            .success(function (data, status, headers, config) {
            })
            .error(function (data, status, header, config) {
            });

        // Reset input fields after submit
        $scope.newItem = {
            name: "",
            priority: "",
            note: ""
        }; 

1 个答案:

答案 0 :(得分:0)

我修改了您的代码以将图像添加到列表中,然后更改了列表项显示以检查属性:

<input type="checkbox" ng-model="item.isChecked" ng-click="editItem()" ng-show="item.hasOwnProperty('isChecked')">
<img ng-show="item.hasOwnProperty('imageSrc')" src="{{ item.imageSrc }}" />

我做了一个简单的函数来添加一个具有imageSrc属性的图像项,在图像中使用,只有在设置了该属性时才会出现。

$scope.list.items.push({
        imageSrc: 'http://lh5.googleusercontent.com/-QErodXkgwBc/AAAAAAAAAAI/AAAAAAAAAWQ/LPUidgUqYHs/photo.jpg?sz=32',
        priority: '',
        note: 'Evan',
        //don't include this property - which will make the ng-show for the checkbox false
        //isChecked: true,
        created: new Date(),
        id: -1
      });

。这是一种方法,但你可以做不同的方式。

样品

'use strict';

var app = angular.module('myApp', ['ngRoute']);
app.constant('API_BASE','/api');
app.config(['$routeProvider', function($routeProvider) {}]);
app.controller('ShoppingListController', ['$scope','$http', '$routeParams', 'API_BASE', '$location', function($scope, $http, $routeParams, API_BASE, $location){

    // GET SPECIFIC LIST
    $scope.list = {items: []};
    $scope.showAddItem = true;
    var id = $routeParams.id;
  //commenting this out because we don't have access to your server
    /*$http({
        method: 'GET',
        url: API_BASE + 'shopping-lists/' + id
    }).then(function successCallback(response) {
        $scope.list = response.data[0];
    }, function errorCallback(response) {
        console.log('it did not work');
        console.log(response.statusText);
    });*/


    // REMOVE LIST
    $scope.removeList = function(){
        var id = $scope.list.id;
        console.log(id);
        $http.delete(API_BASE + 'shopping-lists/' + id)
            .success(function (data, status, headers, config) {
                console.log('you deleted :' + $scope.list);
            })
            .error(function (data, status, header, config) {
            });
        $location.path('/home');    
    };

    // RANDOM ID
    function makeid()     {
        var text = "";
        var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for( var i=0; i < 20; i++ ){
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        text += Date.now();
        return text;
    }


    // ADD ITEM
    $scope.addItem = function(){
        var created = new Date();
        var newID = makeid();

        if($scope.list.hasOwnProperty('items') === false){
            $scope.list.items = [];
        }
        $scope.list.items.push({
            name : $scope.newItem.name,
            priority : $scope.newItem.priority,
            note: $scope.newItem.note,
            isChecked: false,
            listId: $scope.list.id,
            created: created,
            id: newID
        });
        // console.log($scope.list.items);
        $http.put(API_BASE + 'shopping-lists/', $scope.list)
            .success(function (data, status, headers, config) {
            })
            .error(function (data, status, header, config) {
            });

        // Reset input fields after submit
        $scope.newItem = {
            name: "",
            priority: "",
            note: ""
        }; 
    };
    $scope.addImage = function(){
      if($scope.list.hasOwnProperty('items') === false){
            $scope.list.items = [];
        }
      $scope.list.items.push({
        imageSrc: 'http://lh5.googleusercontent.com/-QErodXkgwBc/AAAAAAAAAAI/AAAAAAAAAWQ/LPUidgUqYHs/photo.jpg?sz=32',
        priority: '',
        note: 'Evan',
        //don't include this property - which will make the ng-show for the checkbox false
        //isChecked: true,
        created: new Date(),
        id: -1
      });
    };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>

<div ng-app="myApp" ng-controller="ShoppingListController">
  
  <script src="script.js"></script>
  <button class="btn btn-default btn-custom" href ng-click="showAddItem = !showAddItem" ng-show="!showAddItem">Add Item</button>
  <div style="font-style: italic">//code for adding item
 
  <ul class="list-group">
            <li style="color:{{ list.color }}" class="list-group-item" ng-repeat="item in list.items | orderBy:propertyName:reverse | filter: search ">
                <input type="checkbox" ng-model="item.isChecked" ng-click="editItem()" ng-show="item.hasOwnProperty('isChecked')">
                <img ng-show="item.hasOwnProperty('imageSrc')" src="{{ item.imageSrc }}" />
                {{item.name}} - {{ item.priority }}
                <i class="fa fa-trash-o" aria-hidden="true" ng-click="removeItem(item)"></i>&nbsp;

                <i class="fa fa-pencil" aria-hidden="true" href ng-click="showEdit = !showEdit" ng-show="!showEdit"></i><br>
                <small class="form-text text-muted">Note: {{ item.note }}</small>
                <div ng-show = "showEdit"> 
                    <h4>Edit {{ item.name }}</h4>
                    <form ng-submit="editItem()">
                        <input class="form-control" type="text" name="name" id="name" ng-model="item.name" maxlength="25" required>
                        <select class="form-control" name="priority" id="priority" ng-model="item.priority" required>
                            <option value="">Priority</option>
                            <option value="High">High</option>
                            <option value="Low">Low</option>
                        </select>
                        <input type="text" class="form-control" name="note" id="note" ng-model="item.note" maxlength="255" value= " ">
                        <button class="btn btn-default" type="submit" ng-click="showEdit = !showEdit">Update</button>
                    </form>
                </div>
                <br>

            </li>
        </ul>
        <button ng-click="addImage()" >Add image</button></div>