【问题标题】:how to bind dynamic data to an array in angularJS如何将动态数据绑定到angularJS中的数组
【发布时间】:2017-07-25 05:09:39
【问题描述】:

我是 Angular 的新手。我已经启动了一个购物车 Web 应用程序。所以我从网上找到了一个购物车插件 https://www.codeproject.com/Articles/576246/A-Shopping-Cart-Application-Built-with-AngularJS。但是在这个插件中,我们只能有静态数据。我想要一个从数据库中获取的动态数据。下面是我的代码

default.html

<!doctype html>
<html ng-app="AngularStore">
  <head>
    <title>Shopping Cart with AngularJS</title>

    <!-- Bootstrap, jQuery, Angular-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript" ></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.min.js" type="text/javascript"></script>

    <!-- AngularStore app -->
    <script src="js/product.js" type="text/javascript"></script>
    <script src="js/store.js" type="text/javascript"></script>
    <script src="js/shoppingCart.js" type="text/javascript"></script>
    <script src="js/app.js" type="text/javascript"></script>
    <script src="js/controller.js" type="text/javascript"></script>
    <link href="css/style.css" rel="stylesheet" type="text/css"/>
  </head>

  <body>

    <!-- 
        bootstrap fluid layout
        (12 columns: span 10, offset 1 centers the content and adds a margin on each side)
    -->
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="span10 offset1">
                <h1 class="well" >
                    <a href="default.htm">
                        <img src="img/logo.png" height="60" width="60" alt="logo"/>
                    </a>
                    Angular Store 
                </h1>
                <div ng-view></div>
            </div>
        </div>
    </div>

  </body>
</html>

app.js

'use strict';

// App Module: the name AngularStore matches the ng-app attribute in the main <html> tag
// the route provides parses the URL and injects the appropriate partial page
var storeApp = angular.module('AngularStore', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/store', {
        templateUrl: 'partials/store.htm',
        controller: storeController 
      }).
      when('/products/:productSku', {
        templateUrl: 'partials/product.htm',
        controller: storeController
      }).
      when('/cart', {
        templateUrl: 'partials/shoppingCart.htm',
        controller: storeController
      }).
      otherwise({
        redirectTo: '/store'
      });
}]);
storeApp.factory("DataService", function () {

    // create store
    var myStore = new store();

    // create shopping cart
    var myCart = new shoppingCart("AngularStore");

    // enable PayPal checkout
    // note: the second parameter identifies the merchant; in order to use the 
    // shopping cart with PayPal, you have to create a merchant account with 
    // PayPal. You can do that here:
    // https://www.paypal.com/webapps/mpp/merchant
    myCart.addCheckoutParameters("PayPal", "bernardo.castilho-facilitator@gmail.com");

    // enable Google Wallet checkout
    // note: the second parameter identifies the merchant; in order to use the 
    // shopping cart with Google Wallet, you have to create a merchant account with 
    // Google. You can do that here:
    // https://developers.google.com/commerce/wallet/digital/training/getting-started/merchant-setup
    myCart.addCheckoutParameters("Google", "500640663394527",
        {
            ship_method_name_1: "UPS Next Day Air",
            ship_method_price_1: "20.00",
            ship_method_currency_1: "USD",
            ship_method_name_2: "UPS Ground",
            ship_method_price_2: "15.00",
            ship_method_currency_2: "USD"
        }
    );

    // return data object with store and cart
    return {
        store: myStore,
        cart: myCart
    };
});

store.js

function store() {
    this.products = [

       new product("APL", "Apple", "Eat one every…", 12, 90, 0, 2, 0, 1, 2),
       new product("AVC", "Avocado", "Guacamole…", 16, 90, 0, 1, 1, 1, 2),
       new product("BAN", "Banana", "These are…", 4, 120, 0, 2, 1, 2, 2)      

    ];        

}
store.prototype.getProduct = function (sku) {
    for (var i = 0; i < this.products.length; i++) {
        if (this.products[i].sku == sku)
            return this.products[i];
    }
    return null;
}

在上面的代码中,我们只是传递了一些静态数据,比如苹果鳄梨,而不是那些,我想绑定从数据库中获取的数据。我已经编写了 PHP 代码来获取数据,但我不知道如何将它绑定到数组。即对象产品。

选择.php

<?php
$connect=mysqli_connect("localhost","root","","shopping");

$output=array();

$query="select serial,name,description,price from products";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0)
{
    while ($row=mysqli_fetch_array($result))
     {
        $output[]=$row;
    }
    echo json_encode($output);
}
?>

【问题讨论】:

    标签: javascript php angularjs ajax


    【解决方案1】:

    在您的购物车中添加商品 - (您可以使用 addItem(sku, name, price, quantity) 添加数据,如文章中提到的 additem 用于添加或删除购物车中的商品。在您的数据库调用的响应中使用 addItem。)

    假设您必须在表格列表中添加数据,以便您的“select.php”返回 ListOfData 然后 -

    function yourController($scope,DataService) {
    
    $scope.store = DataService.store;
    //Get Call for the list
    $scope.getList=function(){
      $http({ method: 'GET', url: 'select.php' }).then(function 
      success(response) 
     { 
        alert(response);
       $scope.posts=response.data; 
        for(var i=0;i<$scope.posts.length;i++){
          $scope.store.products.push(new product($scope.posts[i].sku,  
          $scope.posts[i].name, $scope.posts[i].description, 
          $scope.posts[i].price, $scope.posts[i].cal, 
          $scope.posts[i].carot, 
          $scope.posts[i].fiber, $scope.posts[i].folate, 
          $scope.posts[i].potassium,$scope.posts[i].vitc));
        }
      }, function error(response) { 
         // called asynchronously if an error occurs // 
        or server returns response with an error status. 
      } 
    }
    $scope.getList();
    }
    

    如您所见,产品类被创建为

    // product class
    function product(sku, name, description, price, cal, carot, vitc, folate, potassium, fiber) {
        this.sku = sku; // product code (SKU = stock keeping unit)
        this.name = name;
        this.description = description;
        this.price = price;
        this.cal = cal;
        this.nutrients = {
            "Carotenoid": carot,
            "Vitamin C": vitc,
            "Folates": folate,
            "Potassium": potassium,
            "Fiber": fiber
        };
    }
    

    所以我们必须通过创建产品类对象将新数据推送到产品数组中。

    【讨论】:

    • @Namedo Karande 但我们在 store.js 文件中传递了一些静态数据。但是我想传递这些动态数据。我该怎么办?
    • 假设你有一个 api 调用来获取你的 store.js 文件中的 CartData,所以在那个 api 成功函数中你可以使用 addItem。
    • $http({ method: 'GET', url: 'select.php' }).then(function success(response) { alert(response); $scope.posts=response.data; }, function error(response) { // 如果发生错误,则异步调用 // 或者服务器返回带有错误状态的响应。}
    • 我想将此数据绑定到一个名为 product 的对象。
    • new product("BAN", "Banana", "These are...", 4, 120, 0, 2, 1, 2, 2) 我想要响应的动态数据.data 绑定。这个怎么绑定?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2015-02-08
    相关资源
    最近更新 更多