I'm trying to include ng-swicth inside ng-repeat loop - angularjs

I have a menu to navigate through my data model:
<div class="nav">
<span us-spinner ng-if="vm.dataReady == false"></span>
<ul class="nav">
<li ng-repeat="section in vm.data"
ng-class="{'active':vm.activePersonalDataTab == $index}"
ng-click="vm.personalDataTabClick($index)">
{{section.name}}
</li>
</ul>
</div>
Data is a simple object like this one:
personalData: [
{ name: "Общие сведения", src: "CommonInfo/GetCommonInfo", dataType: 0, data: null },
{ name: "Биография", src: null, subNames: [
{ name: "Сведения об образовании", src: "EducationInfo/Read", dataType: 1, data: null },
{ name: "Сведения о службе в вооруженных силах", src: "MilitaryServiceInfo/Read", dataType: 1, data: null },
{ name: "Сведения о семейном положении", src: "FamilyInfo/Read", dataType: 1, data: null },
{ name: "Сведения о судимости", src: "ConvictionInfo/Read", dataType: 1, data: null }
]},
{ name: "Занимаемые должности", src: "PersonPosition/Read", dataType: 1, data: null },
{ name: "Поощрения и взыскания", src: "PromotionRecovery/Read", dataType: 1, data: null },
{ name: "Публикации в СМИ", src: "PublicationInfo/Read", dataType: 1, data: null },
{ name: "Сведения о смерти", src: "DeathInfo/GetDeathInfo", dataType: 0, data: null }
], //dataType: 0 - list, 1 - table
Where 'src' is a name of API controllers. My service using them to get data and then write it in the 'data' property. Now I'm trying to use ng-repeat to loop through all data items and ng-switch to check if it'a one that is selected in my menu (selected menu index is stored in vm.activePersonalDataTab):
<div ng-repeat="section in vm.data" ng-init="sectionIndex=$index" ng-switch="vm.activePersonalDataTab">
<div ng-switch-when="{{sectionIndex}}" ng-switch="vm.data[sectionIndex].dataType">
<div ng-switch-when="0" class="info">
<ul>
<li ng-repeat="item in vm.dict[sectionIndex]" class="{{vm.getLiClass($index)}}"
ng-init="field = vm.getFieldValue(sectionIndex,$index)">
<div class="my-label">{{vm.getFieldName(sectionIndex,$index)}} </div>
<div class="my-info">{{field.type === 1 ? (field.value | date:'dd.MM.yyyy') : field.value}} </div>
</li>
</ul>
</div><!--Если данные представлены простым списком-->
<div ng-switch-when="1" class="table"></div>not yeat<!--Если данные представлены таблицей-->
<div ng-switch-default class="bunch">not yeat</div><!--Если данные представлены набором таблиц-->
</div>
It's works if I change {{sectionIndex}} to 0 in ng-switch-when="{{sectionIndex}}. Byt I whant to use index from ng-repeat for automate this part of my code.

Related

How to add multiple data objects using Array.fill in Angular

I am developing some code using Angular. In my ts file, I have created an array as below
ArrayB= [
{ id: 1, src: 'url' },
{ id: 2, src: 'url' },
{ id: 3, src: 'url' },
{ id: 4, src: 'url' },
{ id: 5, src: 'url' }];
This is ArrayA
ArrayA = Array(5).fill(' ').map((index,_)=>({id:index,src:url}));
I have created grid in HTML file. I want put images (in URL) on each grid tiles.
<mat-grid-list cols="10">
<mat-grid-tile *ngFor="let cell of ArrayA; let i = index">
<div
class="cell"
cdkDropList
[cdkDropListData]="cell"
(cdkDropListDropped)="drop($event)"
[style.background]="i == indexOver ? 'yellowgreen' : 'yellowgreen'"
(mouseover)="this.indexOver = i"
(mouseout)="indexOver = -1" >
<div cdkDrag>
<img
*ngIf="cell.src"
[src]="cell.src"
width="100%"/>
<span *ngIf="!cell.src"></span>
<div *cdkDragPlaceholder></div>
</div>
</div>
</mat-grid-tile>
</mat-grid-list>
So how can I put multiple data objects to ArrayA like ArrayB and assign images to each grid tile.

My nested elements are throwing errors. what am I doing wrong?

The following block renders correctly in the Gutenberg's Block Editor.
registerBlockType('mytheme/rima-preface', {
title: 'Custom block',
description: 'My first block',
category: 'layout',
edit() {
var blockProps = useBlockProps();
return el("div", {
class: "section"
}, el("div", {
class: "container"
}, el("div", {
class: "row align-items-center col-spacing-50"
}, el("div", {
class: "col-12 col-md-6"
}, el("div", {
...blockProps
}, el(InnerBlocks)))
)))
},
save() {
var blockProps = useBlockProps.save();
return el("div", {
class: "section"
}, el("div", {
class: "container"
}, el("div", {
class: "row align-items-center col-spacing-50"
}, el("div", {
class: "col-12 col-md-6"
}, el("div", {
...blockProps
}, el(InnerBlocks.Content)))
)))
}
});
However, as soon as I edit and save it, it shows the following errors on page reload:
Block validation: Expected attribute `class` of value `wp-block-mytheme-rima-preface`, saw `section`.
Block validation: Block validation failed for `mytheme/rima-preface` ({name: "mytheme/rima-preface", icon: {…}, keywords: Array(0), attributes: {…}, providesContext: {…}, …}).
Content generated by `save` function:
<div class="section" class="wp-block-mytheme-rima-preface"><div class="container"><div class="row align-items-center col-spacing-50"><div class="col-12 col-md-6"><div class="wp-block-mytheme-rima-preface"></div></div></div></div></div>
Content retrieved from post body:
<div class="section" class="wp-block-mytheme-rima-preface"><div class="container"><div class="row align-items-center col-spacing-50"><div class="col-12 col-md-6"><div class="wp-block-mytheme-rima-preface">
</div></div></div></div></div>
I've been trying to solve the issue for 30 minutes, anyone that can point me in the right direction?

ng-repeat item limitTo and custom ng-repeat filter item limitTo

Example code
There are three type web, tab and mobile in this json
Target :
1) ng-repeat limitTo:6
2) Type mobile limitTo: 2
{
type: 'web',
data: 'lipsum....'
},
{
type: 'mobile',
data: 'lipsum....'
},
{
type: 'tab',
data: 'lipsum....'
},
{
type: 'web',
data: 'lipsum....'
},
{
type: 'mobile',
data: 'lipsum....'
},
{
type: 'tab',
data: 'lipsum....'
}
Target :
1) ng-repeat limitTo:6
2) Type mobile limitTo: 2
<div ng-repeat="work in works.work | limitTo:6 | filter: ">
Not sure, this is what you required,
<div ng-repeat="res in data|filter:{type:'mobile'} | limitTo:2 ">
{{res.data}}
</div>
Working App

How do you show ng-repeated children of filtered array?

I have a drop-down filtered array, but the array I'd like to use is a little more complex, with nested data, similar to this http://jsfiddle.net/vojtajina/u75us/
I'd like to combine both ideas, but can't figure out why my fiddle doesn't display the 'child nodes'
<div class="col-md-12" ng-controller="App04Ctrl">
<p>Search:
Filter:
<select ng-model="filterItem.store" ng-options="item.name for item in filterOptions.stores">
</select>
Sort:
<select ng-model="sortItem.store" ng-options="item.name for item in sortOptions.stores">
</select>
</p>
<ul>
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter" >Name: {{item.name}} Price: {{item.price}} Location: {{item.location}}</li>
<ul>
<li ng-repeat="package in location.packages">{{package.name}} has services:
<ul>
<li ng-repeat="service in package.services">{{service.name}}</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
angular.js:
var app = angular.module('app04', []);
function App04Ctrl($scope) {
//Contains the filter options
$scope.filterOptions = {
stores: [
{id : 2, name : 'Show All', location: 'All Locations' },
{id : 3, name : 'Ashburn', location: 'Ashburn' },
{id : 4, name : 'San Francisco', location: 'San Francisco' },
{id : 5, name : 'Denver', location: 'Denver' },
{id : 6, name : 'Chicago', location: 'Chicago' },
{id : 7, name : 'Irvine', location: 'Irvine' }
]
};
//Contains the sorting options
$scope.sortOptions = {
stores: [
{id : 1, name : 'Price Highest to Lowest' },
{id : 2, name : 'Price Lowest to Highest' },
]
};
//Mapped to the model to filter
$scope.filterItem = {
store: $scope.filterOptions.stores[0]
}
//Mapped to the model to sort
$scope.sortItem = {
store: $scope.sortOptions.stores[0]
};
//Watch the sorting model - when it changes, change the
//ordering of the sort (descending / ascending)
$scope.$watch('sortItem', function () {
console.log($scope.sortItem);
if ($scope.sortItem.store.id === 1) {
$scope.reverse = true;
} else {
$scope.reverse = false;
}
}, true);
//Custom filter - filter based on the location selected
$scope.customFilter = function (locations) {
if (locations.location === $scope.filterItem.store.location) {
return true;
} else if ($scope.filterItem.store.location === 'All Locations') {
return true;
} else {
return false;
}
};
// Location data
$scope.locations = [{
name: "product1",
price: 198,
location: 'Ashburn',
packages: [{
name: 'Doom Patrol',
services: [{
name: 'Mento'}, {
name: 'Vox'}, {
name: 'Robotman'}]}, {
name: 'Suicide Squad',
services: [{
name: 'King Shark'}]}, {
name: 'Shadowpact',
services: [{
name: 'Zauriel'}, {
name: 'Enchantress'}, {
name: 'Ragman'}, {
name: 'Nightshade'}]}]}, {
name: "product2",
price: 402,
location: 'Chicago',
packages: [{
name: 'Metal Men'}, {
name: 'Legion of Superheroes',
services: [{
name: 'Ultra Boy'}, {
name: 'Kid Quantum'}]}]}, {
name: "product2",
price: 300,
location: 'Denver',
packages: [{
name: 'Freedom Fighters',
services: [{
name: 'Damage'}, {
name: 'Iron Munro'}]}, {
name: 'Birds of Prey',
services: [{
name: 'Huntress'}, {
name: 'Black Alice'}]}]}, {
name: "product2",
price: 1243,
location: 'Irvine',
packages: [{
name: 'The Outsiders'}, {
name: 'Zoo Crew',
services: [{
name: 'Rubberduck'}, {
name: 'Captain Carrot'}]}, {
name: 'The Elite',
services: [{
name: 'Vera Black'}, {
name: 'Manchester Black'}]}, {
name: 'Justice Legion Alpha'}]}
];
}
http://jsfiddle.net/jdacio/Vfx3y/2/
What am I missing? Am I on the right track? is there a better way to do this?
There are two problems that I see in your code above:
[1] Notice that you have closed the <li> tag, thus stopping the nesting of your ng-repeat directive to show the packages and and services of each item location. Simply remove the </li> closing tag and that should solve your first problem.
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter" >
Name: {{item.name}}
Price: {{item.price}}
Location: {{item.location}}
</li> <!-- THIS IS THE PROBLEM!! -->
[2] As what Mosho mentioned, your nested ng-repeat directive is using a location reference which does not exist in the current context of its parent ng-repeat directive. The simplest solution would be to change
<li ng-repeat="package in location.packages">
to
<li ng-repeat="package in item.packages">
The resulting HTML code should be:
<ul>
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter" >
Name: {{item.name}}
Price: {{item.price}}
Location: {{item.location}}
<ul>
<li ng-repeat="package in location.packages">{{package.name}} has services:
<ul>
<li ng-repeat="service in package.services">{{service.name}}</li>
</ul>
</li>
</ul>
</li>
</ul>
Instead of location.packages, it should be item.packages. (or 'location in locations' rather than 'item in locations').
<li ng-repeat="item in locations | orderBy:'price':reverse | filter:customFilter">
...
<li ng-repeat="package in location.packages">
You refer to location, but you declare item in locations.

angularjs controller not binding to partial view

One of the two controllers (AboutCtrl) defined is working as expected. The default controller, TransactionCtrl is paired with the correct partial view but there isn't any angularjs magic happening. For example, I have a simple expression 1 + 2 = {{ 1+2}} that is not resolving (displays as written).
Here's the app definition:
angular.module('pennyWatch', ['ui.bootstrap'])
.config(['$routeProvider', function ($routeProvider) {
return $routeProvider
.when('/', { title: 'Transactions', templateUrl: 'partials/transaction.view.html', controller: TransactionCtrl })
.when('/about', { title: 'About', templateUrl: 'partials/about.view.html', controller: AboutCtrl })
.when('/transaction', { title: 'Transactions', templateUrl: 'partials/transaction.view.html', controller: TransactionCtrl })
.otherwise({ redirectTo: '/' });
}])
Here's the controllers. I can hit a breakpoint in AboutCtrl but not in the other one. I added TransactionCtrl.$inject recently to see if that would help but there isn't a difference:
function TransactionCtrl($scope, $location, logger, ngGrid) {
logger.log("in TransactionCtrl");
$scope.transactionList =
[
{ TransactionID: 1, Title: "TuElectric", Category: "Expense", Amount: "$ 76.80", Date: "Jan 1" },
{ TransactionID: 2, Title: "QT", Category: "Expense", Amount: "$ 62.38", Date: "Jan 1" },
{ TransactionID: 3, Title: "Kroger", Category: "Expense", Amount: "$ 123.67", Date: "Jan 3" },
{ TransactionID: 4, Title: "All State", Category: "Expense", Amount: "$ 248.17", Date: "Jan 3" },
{ TransactionID: 5, Title: "Credit Union", Category: "Income", Amount: "$1,897.00", Date: "Jan 4" }
];
$scope.error = "";
$scope.gridOptions = {
data: "transactionList"
//, showGroupPanel: true
};
}
TransactionCtrl.$inject = ['$scope', '$location', 'logger', 'ngGrid'];
function AboutCtrl($scope, logger) {
$scope.logEntries = logger.logEntries;
}
The partial view:
<!-- Transaction page partial view -->
<div style="position: absolute; top: 20px; left:2em;">
About
</div>
<p class="error" data-ng-show="error.length">{{error}}</p>
<br/>
<article>
<header>
<h2>Transaction List</h2>
</header>
<p>(trnx view) 1 + 2 = {{ 1 + 2 }}</p>
<ul id="fauxTable">
<li>
<p><span>Title</span><span>Category</span><span>Amount</span><span>Date</span></p>
</li>
<li data-ng-repeat="item in transactionList">
<p><span>{{item.Title}}</span><span>{{item.Category}}</span><span>{{item.Amount}}</span><span>{{item.Date}}</span></p>
</li>
</ul>
</article>
<article>
<h2>Transaction List (ngGrid)</h2>
<div class="gridStyle" ng-grid="gridOptions">
</div>
</article>
Thanks!

Resources