2015-05-24 84 views
0

這是我的代碼:AngularJS,形式和顯示JSON數據

PizzaStore.html

<!DOCTYPE html> 
    <html ng-app="PizzaApp"> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
     <title>Cool pizza for everyone!</title> 
     <link href="Site.css" rel="stylesheet" /> 

     <script src="js/angular.min.js"></script> 
     <script src="js/angular-route.min.js"></script> 
     <script src="js/App.js"></script> 
    </head> 
    <body> 

      <div> 

         <a href="#/">Home</a> 
         <a href="#confirm/">Send order</a> 
      </div> 
      <br /> 
     <div ng-view></div> 

    </body> 
    </html> 

Pizzas.html

<div id="content"> 
     <div class="item" ng-repeat="pizza in pizzas"> 
      <p>{{pizza.name}}</p> 
      <img src="{{pizza.src}}" /> 
      <div align="center" ng-if="pizza.available === true"><span ng-click="increment($index)">+</span> {{pizza.count}} <span ng-click="decrement($index)">-</span></div> 
      <p style="color: red" ng-if="pizza.available === false">Unavailable</p> 
     </div> 
    </div> 

App.js

var PizzaApp = angular.module('PizzaApp', ['ngRoute']); 

var model = [{ "name":"Pizza one", "src":"/images/1.jpg", "available": true}, 
     { "name":"Pizza two", "src":"/images/2.jpg", "available": true }, 
     { "name":"Pizza three", "src":"/images/3.jpg", "available": true}, 
     { "name":"Pizza four", "src":"/images/4.jpg", "available": false}]; 

PizzaApp.config(function ($routeProvider) { 
    $routeProvider 

     .when('/', { 
      templateUrl: 'Pizzas.html', 
      controller: 'pizzasController' 
     }) 

     .when('/confirm', { 
      templateUrl: 'Confirm.html', 
      controller: 'confirmController' 
     }); 
}); 

PizzaApp.controller('pizzasController', function ($scope) { 

    $scope.pizzas = model; 
    for (var i = 0; i < $scope.pizzas.length; i++) { 
     $scope.pizzas[i].count = 0; 
    } 

    $scope.increment = function (index) { 
     $scope.pizzas[index].count += 1; 
    }; 

    $scope.decrement = function (index) { 
     if ($scope.pizzas[index].count >0) 
      $scope.pizzas[index].count -= 1; 
    }; 
}); 

PizzaApp.controller('confirmController', function ($scope) { 


}); 

它工作正常,顯示數據,但我想從PizzaStore.htmlConfirm.html(現在它是空的)在JSON發送新模型。之後,我想在該視圖上顯示JSON數據。我一直試圖以多種方式解決這個問題,但仍然找不到合適的解決方案。

如果有可能不回答這個問題,如:您可以使用...。看到真正的解決方案會更有用。


非常感謝您的關注!

+1

如果你想在控制器之間共享模型,你應該看看編寫一個角度服務來保存你的模型實例。然後,您可以將該服務注入您的控制器以檢索您感興趣的模型。 – mindparse

回答

0

創建服務:

PizzaApp.service('orderService', [orderService]); 

function orderService(){ 
    var _order = undefined; 

    return { 
     getOrder: function(){ 
      if(typeof _order !== 'undefined'){ 
       return _order; 
      } 
     }, 
     setOrder: function(order){ 
      _order = order; 
     } 
    } 
} 

然後注入服務爲你的控制器,當用戶點擊確認訂單,你會設定orderService.setOrder(順序)的並檢索它的確認訂單頁orderService.getOrder()