我正在做一个简单的购物车系统。
我创建了一个表格,用于显示每个产品侧面的添加到购物车按钮的产品。当我点击按钮时,我能够获得每个产品的索引,但我无法获取对象内的数据(名称,价格和数量)。请帮忙!我怎么能得到它们?感谢。
< script >
var app = angular.module("shoppingCart", []);
app.controller("cartCtrl", function($scope) {
$scope.products = [{
id: 1,
name: 'Baby Mix Lobster (300g - down)',
unit: 'per kg',
price: 2500,
qty: 1
},
{
id: 2,
name: 'Tiger Lobster (1kg - up)',
unit: 'per kg',
price: 5800,
qty: 1
},
{
id: 3,
name: 'Tiger Lobster (700g - 999g)',
unit: 'per kg',
price: 4500,
qty: 1
},
{
id: 4,
name: 'Tiger Lobster (500g-699g)',
unit: 'per kg',
price: 4200,
qty: 1
},
{
id: 5,
name: 'Tiger Lobster (300g-499g)',
unit: 'per kg',
price: 3900,
qty: 1
},
];
$scope.addToCart = function(item) {
alert(item);
}
});
<
/script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<table style="border: 1px solid black">
<tr>
<th></th>
<th>name</th>
<th>unit</th>
<th>price</th>
<th>Qty</th>
<th></th>
</tr>
<tr ng-repeat="x in products">
<td>{{$index + 1}}</td>
<td>{{x.name}}</td>
<td>{{x.unit}}</td>
<td>{{x.price | currency: "Php " : 2}}</td>
<td><input type="number" min="1" placeholder="{{x.qty}}" /></td>
<td><button ng-click="addToCart($index)">Add to Cart</button></td>
</tr>
</table>
</div>
答案 0 :(得分:0)
需要传递商品index
而不是ng-click="addToCart(x)"
import * as React from 'react'; // eslint-disable-line import/no-extraneous-dependencies
import styled from 'styled-components'; // eslint-disable-line import/no-extraneous-dependencies
import Label from '../Label/Label';
const ToggleButtonController = styled.button`
background-color: red;
`;
const ToggleInputController = styled.input`
background-color: red;
`;
const Toggle = (props) => {
const { label } = props;
let toggleControllerRef = null;
const renderLabel = () => {
return (
<Label
onClick={() => { toggleControllerRef.click(); }} // <--- untested line where I invoke the input element click event on label click
>
{ label }
</Label>
);
};
const renderController = () => {
const { labelPosition, disabled, type, onClick, onChange } = props;
let controller = (
<div>
<ToggleInputController
onClick={onClick}
onChange={onChange}
innerRef={(toggleController) => { toggleControllerRef = toggleController; }}
type={type === 'switch' ? 'checkbox' : type}
disabled={disabled}
/>
</div>
);
if (type === 'button') {
controller = (
<div>
<ToggleButtonController
onClick={onClick}
disabled={disabled}
{...commonUtils.filterProps(Toggle.propTypes, props)}
>
{ label }
</ToggleButtonController>{ renderRequired() }
</div>
);
}
return controller;
};
return (
<div>
{
renderController()
}
</div>
);
};
export default Toggle;
答案 1 :(得分:0)
如果能够获取索引,那么为什么不从数组中获取对象?
$scope.addToCart = function(index) {
var item = $scope.products[index];
// access the properties of `item` here.
}
此外,建议跟踪ng-repeat
:
ng-repeat="x in products track by $index"