Angular 1.5 component demo

by nickadeemus2002

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
<div ng-app="demoApp" ng-controller="MainController as mainCtrl">
  <h3>{{order.product.name}} ($ {{order.product.costPerItem}})</h3>
  <div>
    <label>Quantity</label>
    <select class="form-control"
            ng-model="order.quantity"
            ng-options="quantity for quantity in allowedQuantities"
    >
     <!-- 
     loop over allowedQuantities, and for each element, assign a 
     variable called quantity (to use later), and then display 
     quantity (type number). angularJS compares 'for quantity' with
     order.quantity.  this works because angular is comparing a number.
     --> 
    </select>
  </div>
  <div>
    <label>Shipping Method</label>
    <select class="form-control"
            ng-model="order.shipment"
            ng-options="shipment.name for shipment in shipmentMethods">
    <!-- a
      ngularJS is doing a simple comparison on objects.  needs different handling.
      -->
    </select>
  </div>
  <div>
  <h3>Total Cost: </h3>
    ${{calculateTotalCost(order)}}
  </div>  
</div>

JavaScript

//selects
var app = angular.module('demoApp', []);
app.controller('MainController', ['$scope', 'dataSource',
  	function($scope, dataSource){
    
  		$scope.order = dataSource.order;
    	$scope.allowedQuantities = dataSource.order.product.allowedQuantities;
    	$scope.shipmentMethods = dataSource.shipmentMethods;
    
    	$scope.calculateTotalCost = function(order){
    		return(order.product.costPerItem * order.quantity) + order.shipment.flatCost;
    	};
    
    //force angular to reference the same object we have stored
    angular.forEach($scope.shipmentMethods, function( shipment){
    	if(shipment.shipmentId == $scope.order.shipment.shipmentId) {
      	$scope.order.shipment = shipment; 
      }
    });
 }]);
 
 app.provider('dataSource',[ function(){
  	var sampleOrder = {
    	product: {
      	productId: "p1",
        name: "Angular Demo Part 1",
        costPerItem: 25,
        allowedQuantities: [1,2,3,4,5]
      },
      quantity: 3,
      shipment : {shipmentId: 2, name: "Express Mail", flatCost: 10}
    };
    var sampleShipmentMethods = [
    	 {shipmentId: 1, name: "Regular Mail", flatCost: 5},
       {shipmentId: 2, name: "Express Mail", flatCost: 10},
       {shipmentId: 3, name: "Priority Mail", flatCost: 15}
    ];
    
    return {
    	$get:function(){
      	return {
        	order: sampleOrder,
      		shipmentMethods: sampleShipmentMethods
        }
      }
    }
  }]);


function MainController(xyzApi) {
	var vm = this;
  vm.test = '';
 
}