根据angularjs中的点击次数更新视图

时间:2018-04-16 19:20:17

标签: angularjs

我想更新我的视图(输入表单)以将产品添加到数据库。对于单个产品,我可以通过将其添加到数组中来添加它,但现在我想添加多个产品,只需单击“添加更多产品”按钮,就会在下面生成类似的视图(表单)现有表格,这可以多次(在运行时确定)。现在我有两个问题: 1.如何使用每个(添加更多产品)按钮单击更新我的视图。它是通过维持一些计数来完成的吗? 2.如何将每个表单中的多个产品值添加到对象数组中。

$scope.onClick = function () {
                        $scope.productData =
                                {
                                    name: $scope.name,
                                    description: $scope.description,
                                    price: $scope.price,
                                    image: $scope.image,
                                    tags: $scope.tags,
                                    partner_id: $scope.partner_id,

                                };
                                }

1 个答案:

答案 0 :(得分:1)

示例代码

有很多方法可以做到这一点。我制作了这个示例plunker,它显示了一个简单的选项,即切换表单div,在表单中添加数据,然后将生成的表单对象推送到主产品数组。

编辑: 我重构了我的plunk和snippet以使用Javascript类和构造函数。如下所示克隆主对象是执行此任务的另一种方法。

https://embed.plnkr.co/IsNifSaF8jE7oOog29dK/

(请参阅此答案底部的完整摘要。)

说明

在您的代码中,您在所有对象属性上使用$ scope。您实际应该做的是创建一个顶级范围数组,该数组是从服务器检索产品的结果。我实际上会创建一个JavaScript构造函数/类,它匹配数据库中所需的产品对象(为简洁起见,我只是创建了一个“master”对象和一个克隆的“newProduct”对象来进行编辑):

// Sample Product Object
$scope.newProduct= {
  name: "",
  description: "",
  price: 0.00,
  image: "",
  tags: [],
  partner_id: 0
};

您可以使用$scope.newProductng-model对象绑定到表单。

<!-- ==== Simplified Form ==== -->
<form class="form" ng-submit="submitNewProduct()">
  <div class="form-group">
    <label>Product Name: </label>
    <input class="form-control" type="text" ng-model="newProduct.name" >
   </div>
   <input type="submit" class="btn btn-info" />
</form>

现在,当您提交新产品数据时,您可以在控制器中操作它(通过$scope.submitNewProduct()功能)。将对象成功插入数据库并完成操作数据后,可以将最终的“新产品”对象推送到products数组中。一旦您将新产品添加到阵列,AngularJs将为您更新视图(通过ng-model绑定的对象正在进行更改):

// If server update is successful, add new product to products array
$scope.products.push($scope.newProduct);

如果您没有使用构造函数,请务必注意我将$scope.newProduct对象重置为默认值,这样当您再次打开新产品表单时,它不会带来任何新的更改。

// Reset placeholder product
$scope.newProduct = $scope.masterProduct;

有用的资源

(function() {
  "use strict";

  var app = angular.module("myApp", []);

  app.controller("myController", myController);

  myController.$inject = ["$scope", "$timeout", "$filter"];

  function myController($scope, $timeout, $filter) {
    $scope.loading = false;
    
     class Product {
      constructor(_name, _description, _price) {
        this.id = this.getNewId();
        this.name = _name;
        this.description = _description;
        this.price = _price;
        this.image = "https://www.thesweetexplosion.co.uk/wp-content/uploads/2013/06/product-placeholder.jpg";
        this.tags = [];
        this.partner_id = 0;
      }
      
      getNewId() {
        var latestId = $scope.products[$scope.products.length - 1].id
        return latestId + 1;
      }
    }

    // Pretending we received these products received from the database...
    $scope.products = [{
      id: 0,
      name: "product_1",
      description: "product_1 description",
      price: 52.23,
      image: "https://raspberrypi.dk/wp-content/uploads/2014/07/raspberry-pi-model-b-plus1.png",
      tags: [],
      partner_id: 345214967
    }, {
      id: 1,
      name: "product_2",
      description: "product_2 description",
      price: 46.23,
      image: "https://modtronix.com.au/wp-content/uploads/enc-rpi3-official_bottom_ll-100x100.jpg",
      tags: [],
      partner_id: 514852924
    }];
    
    // Add new Products by using this base object
    $scope.placeholderProduct = {
      id: 0,
      name: "",
      description: "",
      price: 0.00,
      image: "https://www.thesweetexplosion.co.uk/wp-content/uploads/2013/06/product-placeholder.jpg",
      tags: [],
      partner_id: 0
    };
    
    $scope.createNewProduct = function(){
      $scope.newProduct = new Product("", "", 0);
    }

    $scope.submitNewProduct = function() {
      // DO SERVER UPDATING HERE
      
      // Show loading
      $scope.updating = true;

      // Simulate server update
      $timeout(function() {

        // If server update is successful, add new product to products array
        $scope.products.push($scope.newProduct);

        // Reset submit button
        $scope.updating = false;

        // Reset placeholder product
        $scope.newProduct = {};

        // Hide products form
        $scope.addProductForm = false;

      }, 1000);

    }

  }

})();
.productImg {
  width: 50px;
  height: 50px;
}

.prodForm {
  margin-top: 15px;
  margin-bottom: 15px;
  ;
}
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.1/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://use.fontawesome.com/releases/v5.0.9/js/all.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp" ng-controller="myController">
    <div class="container">
      <div class="row">
        <div class="col-xs-12">
          <div class="jumbotron text-center">
            <h3>AngularJS (1.3.1) - Instantiating Products with ES6 Class Constructor</h3>
          </div>
        </div>
      </div>
      
      <!-- New Product Form - Toggled with addProductForm -->
      <div class="col-xs-12">
        <button type="button" class="btn btn-sm btn-success" ng-click="createNewProduct(); addProductForm = !addProductForm" ng-show="!addProductForm">
           <span class="glyphicon-plus">  Add New Product</span>
          </button>
          <button type="button" class="btn btn-sm btn-danger" ng-click="addProductForm = !addProductForm" ng-show="addProductForm">
            <span>Clear</span>
          </button>
        </div>
       <div class="col-xs-12 well prodForm" ng-show="addProductForm">
        <form class="form" ng-submit="submitNewProduct()">
          <div class="form-group">
            <label>Product Name: </label>
            <input class="form-control" type="text" ng-model="newProduct.name" >
          </div>
          <div class="form-group">
            <label>Description: </label>
            <input class="form-control" type="text" ng-model="newProduct.description" />
          </div>
          <div class="form-group">
            <label>Price: </label>
            <input class="form-control" type="number" min="0.01" step="0.01" ng-model="newProduct.price" format="currency" />
          </div>
          <div class="form-group">
            <label>Partner Id: </label>
            <input class="form-control" type="number" ng-model="newProduct.partner_id" />
          </div>
          <input type="submit" class="btn btn-info" ng-show="!updating" />
          <button type="button" class="btn btn-info" ng-show="updating"><i class="fa fa-spinner fa-spin"></i>  Updating...</button>
        </form>
      </div>
      
       <!-- Primary Products Table -->
      <div class="col-xs-12">
        <table class="table table-striped">
          <thead>
            <tr>
              <th>Name</th>
              <th>Description</th>
              <th>Price</th>
              <th>Image</th>
              <th>Tags</th>
              <th>Partner Id</th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="product in products track by $index">
              <td>{{ product.name }}</td>
              <td>{{ product.description }}</td>
              <td>{{ product.price | currency }}</td>
              <td>
                <img class="productImg" ng-src="{{ product.image }}" alt="{{ product.name }} img" />
              </td>
              <td>{{ product.tags }}</td>
              <td>{{ product.partner_id }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </body>

</html>