我有一个json结构:
let total_price = "£100";
let product_groups = [
{
"name": "group 1",
"summary": "group 1 summary",
"products": [
{
"name": "product 1",
"price": "£10",
...
},
...
]
},
...
]
我正在尝试将其展平并使用以下形式的表格进行显示
<table class="table">
<thead>
<tr>
<th>Group Name</tr>
<th>Product Name</tr>
<th>Product Price</tr>
</tr>
</thead>
<tbody>
<tr ng-repeat="group in product_groups">
<td>{{group.name}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}<td>
</tr>
<tr>
<th colspan="2">Total</th>
<td>{{total_price}}</td>
</tr>
</tbody>
</table>
但是,这显然不能让我访问每个产品。有没有办法使用ng-repeat
来做到这一点?还是我需要先在控制器中展平数据结构?
答案 0 :(得分:2)
您可以使用嵌套的ng-repeat' and use
ng-repeat-start and
ng-repeat-end`尝试以下操作。
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.product_groups = [ { "name": "group 1", "summary": "group 1 summary", "products": [ { "name": "product 1", "price": "£10", }, { "name": "product 1", "price": "£10", }, ] }, { "name": "group 2", "summary": "group 2 summary", "products": [ { "name": "product 21", "price": "£20", }, { "name": "product 15", "price": "£80", }, ] } ];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<table class="table">
<thead>
<tr>
<th>Group Name</th>
<th>Product Name</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
<tr ng-repeat-start="group in product_groups"></tr>
<tr ng-repeat="product in group.products">
<td>{{group.name}}</td>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
</tr>
<tr ng-repeat-end></tr>
</tbody>
</table>
</div>
</body>
答案 1 :(得分:1)
您好,尝试以下解决方案
$scope.newArray = [];
let product_groups = [
{
"name": "group 1",
"summary": "group 1 summary",
"products": [
{
"name": "product 1",
"price": "£10",
},
]
},
];
for(var i = 0; i< product_groups.length; i++) {
for(var j =0; j< product_groups[i].products.length; j++) {
var flattenProduct = {
gname:product_groups[i].name,
name:product_groups[i].products[j].name,
price : product_groups[i].products[j].price
};
$scope.newArray.push(flattenProduct );
}
}
然后按如下所示调用html:
<table class="table">
<thead>
<tr>
<th>Group Name</tr>
<th>Product Name</tr>
<th>Product Price</tr>
</tr>
</thead>
<tbody>
<tr ng-repeat="p in newArray">
<td>{{p.gname}}</td>
<td>{{p.name}}</td>
<td>{{p.price}}<td>
</tr>
</tbody>
</table>
答案 2 :(得分:1)
您应该展平JSON。我建议从以下位置更改您的结构:
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.google.android.gms.maps.GoogleMap;
// change this to that for your package
import project.your_package_name.org.R;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Tools {
public static void setSystemBarColor(Activity act) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = act.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(act.getResources().getColor(R.color.colorPrimaryDark));
}
}
public static void setSystemBarColor(Activity act, @ColorRes int color) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = act.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(act.getResources().getColor(color));
}
}
public static void setSystemBarLight(Activity act) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View view = act.findViewById(android.R.id.content);
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
}
}
public static void clearSystemBarLight(Activity act) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Window window = act.getWindow();
window.setStatusBarColor(ContextCompat.getColor(act, R.color.colorPrimaryDark));
}
}
/**
* Making notification bar transparent
*/
public static void setSystemBarTransparent(Activity act) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = act.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.argb(255, 255, 234, 187));
}
}
public static void displayImageOriginal(Context ctx, ImageView img, @DrawableRes int drawable) {
try {
Glide.with(ctx).load(drawable)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(img);
} catch (Exception e) {
}
}
public static void displayImageRound(final Context ctx, final ImageView img, @DrawableRes int drawable) {
try {
Glide.with(ctx).load(drawable).asBitmap().centerCrop().into(new BitmapImageViewTarget(img) {
@Override
protected void setResource(Bitmap resource) {
RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(ctx.getResources(), resource);
circularBitmapDrawable.setCircular(true);
img.setImageDrawable(circularBitmapDrawable);
}
});
} catch (Exception e) {
}
}
public static void displayImageOriginal(Context ctx, ImageView img, String url) {
try {
Glide.with(ctx).load(url)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(img);
} catch (Exception e) {
}
}
public static String getFormattedDateSimple(Long dateTime) {
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy");
return newFormat.format(new Date(dateTime));
}
public static String getFormattedDateEvent(Long dateTime) {
SimpleDateFormat newFormat = new SimpleDateFormat("EEE, MMM dd yyyy");
return newFormat.format(new Date(dateTime));
}
public static String getFormattedTimeEvent(Long time) {
SimpleDateFormat newFormat = new SimpleDateFormat("h:mm a");
return newFormat.format(new Date(time));
}
public static String getEmailFromName(String name) {
if (name != null && !name.equals("")) {
String email = name.replaceAll(" ", ".").toLowerCase().concat("@mail.com");
return email;
}
return name;
}
public static int dpToPx(Context c, int dp) {
Resources r = c.getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
public static GoogleMap configActivityMaps(GoogleMap googleMap) {
// set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setScrollGesturesEnabled(true);
googleMap.getUiSettings().setMapToolbarEnabled(true);
return googleMap;
}
public static void copyToClipboard(Context context, String data) {
ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("clipboard", data);
clipboard.setPrimaryClip(clip);
Toast.makeText(context, "Text copied to clipboard", Toast.LENGTH_SHORT).show();
}
public static void nestedScrollTo(final NestedScrollView nested, final View targetView) {
nested.post(new Runnable() {
@Override
public void run() {
nested.scrollTo(500, targetView.getBottom());
}
});
}
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static boolean toggleArrow(View view) {
if (view.getRotation() == 0) {
view.animate().setDuration(200).rotation(180);
return true;
} else {
view.animate().setDuration(200).rotation(0);
return false;
}
}
public static boolean toggleArrow(boolean show, View view) {
return toggleArrow(show, view, true);
}
public static boolean toggleArrow(boolean show, View view, boolean delay) {
if (show) {
view.animate().setDuration(delay ? 200 : 0).rotation(180);
return true;
} else {
view.animate().setDuration(delay ? 200 : 0).rotation(0);
return false;
}
}
public static void changeNavigateionIconColor(Toolbar toolbar, @ColorInt int color) {
Drawable drawable = toolbar.getNavigationIcon();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
public static void changeMenuIconColor(Menu menu, @ColorInt int color) {
for (int i = 0; i < menu.size(); i++) {
Drawable drawable = menu.getItem(i).getIcon();
if (drawable == null) continue;
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
}
public static void changeOverflowMenuIconColor(Toolbar toolbar, @ColorInt int color) {
try {
Drawable drawable = toolbar.getOverflowIcon();
drawable.mutate();
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
} catch (Exception e) {
}
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
public static String toCamelCase(String input) {
input = input.toLowerCase();
StringBuilder titleCase = new StringBuilder();
boolean nextTitleCase = true;
for (char c : input.toCharArray()) {
if (Character.isSpaceChar(c)) {
nextTitleCase = true;
} else if (nextTitleCase) {
c = Character.toTitleCase(c);
nextTitleCase = false;
}
titleCase.append(c);
}
return titleCase.toString();
}
public static String insertPeriodically(String text, String insert, int period) {
StringBuilder builder = new StringBuilder(text.length() + insert.length() * (text.length() / period) + 1);
int index = 0;
String prefix = "";
while (index < text.length()) {
builder.append(prefix);
prefix = insert;
builder.append(text.substring(index, Math.min(index + period, text.length())));
index += period;
}
return builder.toString();
}
}
`
至:
product_groups = [{
"name": "group 1",
"summary": "group 1 summary",
"products": [{
"name": "product 1",
"price": "£10"
},
{
"name": "product 2",
"price": "£20"
}
]
}]
然后您可以简单地使用以下示例:
product_groups = [{
"name": "group 1",
"summary": "group 1 summary",
"product": {
"name": "product 1",
"price": "£10"
}
},
{
"name": "group 1",
"summary": "group 1 summary",
"product": {
"name": "product 2",
"price": "£20"
}
}
]
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.product_groups = [{
"name": "group 1",
"summary": "group 1 summary",
"product": {
"name": "product 1",
"price": "£10",
}
},
{
"name": "group 1",
"summary": "group 1 summary",
"product": {
"name": "product 2",
"price": "£20",
}
}
]
});
答案 3 :(得分:-1)
在现有的ng-repeat中使用新的ng-repeat,例如嵌套循环。