How to delete item from array angularjs? - arrays

Why I can't remove item from array posts?
html tag for delete item
html tag
<span ng-click="remove($index)"> delete</span>
//AngularJS method where I try to delete item
blog.remove = function(index) {
blog.posts.splice(index, 1);
};
//Angular array posts
blog.posts = [{
"title": "Blog Post One",
"comments": [
{
"body":"Lorem ipsum dolor sit amet, consectetur adipisicing elit. ",
"author": "trollguy87"
}
]}];
Where can be problem?

Try passing the item to the function and getting the index from the item.
As mentioned in the below thread.
How do I delete an item or object from an array using ng-click?

If you are using ng-repeat then this can help:
<div ng-repeat="key in posts"> <!-- This will use your blog.posts -->
<button ng-click="posts.splice($index, 1)">
{{key.title}}
</button>
</div>

Related

React JS - JSX returns [object Object] instead of string

Why this JSX hook returns [object Object] [object Object] instead of HTML string?
export default function Article (props) {
const {
content,
} = props;
console.log({content});
return (
<>
<div>
{content.replace(/<p>(.*?)<\/p>/g, (match) => {
return (
<p className="text-black">{match}</p>
);
})}
</div>
</>
)
}
Console.log print:
{
content: '<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas dignissim ac ante nec hendrerit.</p>\n' +
'\n' +
'<p>Morbi rhoncus diam quis sodales iaculis. Morbi ullamcorper consectetur ultricies. Nam vel efficitur erat.</p>'
}
Issue
Why this JSX hook returns [object Object] [object Object] instead of
HTML string?
You are attempting to render the returned of content.replace but the function you use to replace is returning a JSX object instead of a new string. You are also copying the entire match instead of just the captured group.
Solution
It is very unclear to me what you are trying to do, or why, but if you want to modify the raw HTML you can do a string replace, but you need to then use standard HTML (not JSX!!) and set the innerHTML of the div. Here you need to specify class instead of className.
<div
dangerouslySetInnerHTML={{
__html: content.replace(/<p>(.*?)<\/p>/g, (match, p1) => {
return `<p class="text-black">${p1}</p>`;
})
}}
></div>
or a bit more simple without the updater function
<div
dangerouslySetInnerHTML={{
__html: content.replace(/<p>(.*?)<\/p>/g, '<p class="text-black">$1</p>')
}}
></div>
Demo

Get about -> title and about -> images -> name from my local .json file

I want to show all images in my app.component.html file using *ngFor loop.
This is my app.component.html
<app-nav></app-nav>
<div class="container mt-4">
<router-outlet></router-outlet>
</div>
<ul>
<li *ngFor="let users of Users">
<h2>{{users.name}}</h2>
</li>
</ul>
This is my data.json
{
"about": {
"title":"STORY ABOUT US",
"subtitle":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et",
"images":[
{
"name":"aa1.jpg",
"id":1,
"link":"http://google.com/",
"icon":"fa fa-link"
},
{
"name":"aa2.jpg",
"id":2,
"link":"http://google.com/",
"icon":"fa fa-link"
}
]
}
This is my app.component.ts
import { Component } from '#angular/core';
import sampleData from '../assets/data.json';
#Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })
export class AppComponent { Users: any = sampleData; }
Given your JSON data the component template should look like the following:
<h1>{{users.about.title}}</h1>
<ul>
<li *ngFor="let image of users.about.images">
{{image.name}}
</li>
</ul>
You want to loop over the iterable in your JSON data which is the images property and that is what *ngFor allows.
See a working stackblitz demo I made with the above description.
Note I used the property name users lowercase, instead of Users uppercase, as it is a more common convention, but still an opinion.
you can access your object property using two ways
1
object.propertyName
2
object['propertyName']
so import your json file into your object and access its properties like that
<li *ngFor="let users of Users">
<h2>{{users.name}}</h2>
<h2>{{users.title}}</h2>
<h2>{{users.image.name}}</h2>
<h2>{{users.image.id}}</h2>
</li>

How to change icon marker with angularjs and google maps

im working in phonegap project with angularjs google maps (https://github.com/allenhwkim/angularjs-google-maps)
I need to change default icon marker with custom images.
This is my controller code:
core.js
// Map Markers Controller
app.controller('markersController', function($scope, $compile){
$scope.infoWindow = {
title: 'title',
content: 'content'
};
$scope.markers = [
{
'title' : 'Location #1',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7112, -74.213]
},
{
'title' : 'Location #2',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7243, -74.2014]
},
{
'title' : 'Location #3',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7312, -74.1923]
}
];
$scope.showMarker = function(event){
$scope.marker = $scope.markers[this.id];
$scope.infoWindow = {
title: $scope.marker.title,
content: $scope.marker.content
};
$scope.$apply();
$scope.showInfoWindow(event, 'marker-info', this.getPosition());
}
});
And this is my markers.html
<div ng-controller="markersController" class="map-fullscreen-container">
<map zoom="8" center="[-26.82, -54.84]" class="fullscreen">
<info-window id="marker-info">
<div ng-non-bindable="">
<strong class="markerTitle">{{ infoWindow.title }}</strong>
<div class="markerContent">
<p>{{ infoWindow.content }}</p>
</div>
</div>
</info-window>
<marker ng-repeat="(id, marker) in markers" id="{{ id }}"
position="{{marker.location}}"
on-click="showMarker(event, $index)" >
</marker>
</map>
</div>
If you only have one marker, you can set it up directly on your marker directive:
<marker ng-repeat="(id, marker) in markers" id="{{ id }}"
position="{{marker.location}}"
on-click="showMarker(event, $index)"
icon="yourIconUrl.png" >
</marker>
If you have different markers for each item, the first thing you need to do is to add the icon property to your items:
$scope.markers = [
{
'title' : 'Location #1',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7112, -74.213],
'icon' : 'yourIconUrl.png'
},
{
'title' : 'Location #2',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7243, -74.2014],
'icon' : 'yourIconUrl.png'
},
{
'title' : 'Location #3',
'content' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a viverra magna',
'location' : [40.7312, -74.1923],
'icon' : 'yourIconUrl.png'
}
];
Then you need to use it on your html, by adding it to the marker directive:
<marker ng-repeat="(id, marker) in markers" id="{{ id }}"
position="{{marker.location}}"
on-click="showMarker(event, $index)"
icon="{{marker.icon}}" >
</marker>
That's it, hope that helps.
Please refer to the documentation for more info:
https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/docs/index.html

AngularJS - hide/show div if date is within last 6 months

I have an ng-repeat that displays a list of dates, and information about purchases on that dates.
HTML:
<div ng-repeat="data in MyData">
<p>
{{ data.purchasedOn.substring(6, data.purchasedOn.length - 2) | date:'dd/MM/yyyy' }}
</p>
<br>
<p>
{{ data.purchaseDescription }}
</p>
</div>
Which displays:
01/02/2013
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"
10/04/2014
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"
02/08/2014
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"
13/06/2014
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"
19/02/2013
"Lorem ipsum dolor sit amet, consectetur adipisicing elit"
How can i only show the {{ data.purchaseDescription }} when purchasedOn is within the last 6 months from the current month?
Assuming that you want to show purchasedOn but not the description, you could use a function like this one described here to determine a date 6 months prior.
function addMonths(date, months) {
date.setMonth(date.getMonth() + months);
return date;
}
Then define a function to get a boolean show/hide value:
function shouldHide(purchasedOn){
var purchaseDate = Date.parse(purchasedOn);
var sixMonthsAgo = addMonths(new Date(), -6);
var hide = purchaseDate < sixMonthsAgo ? true : false;
return hide;
}
Now you can just use your function in an ng-hide in your <p> element
<p ng-hide={{shouldHide(data.purchasedOn)}}>
{{ data.purchaseDescription }}
</p>
EDIT
If you do just want to hide the entire element, you could make a filter function like this:
$scope.filterOldDates = function(date)
{
if(shouldHide(date)){
return false;
}
return true;
};
You would use it like this:
<div ng-repeat="data in MyData | filterOldDates">

Filter date range using jQuery UI calendars in AngularJS data-bound table

I have a series of HTML tables which pull data from JSON sources. These are tabbed. They work fine and can be seen in the fiddle here:
Fiddle: http://jsfiddle.net/nA28B/1/.
What I need to do now though is use the date range inputs (which are integrated as jQuery UI datepickers) to filter the data in the tables by the date column. I'm new to AngularJS and the integration with the jQuery UI datepickers particularly has taken this way over my head and I'm struggling to find the solution.
I've tried adding an ng-change attribute to the date inputs but can't even get this to fire a simple alert - possibly I've not set up controllers in the correct places (I've tried creating a new controller around the filter inputs to no avail)?
The code for this is pretty lengthy but quite straight forward, as follows:
HTML:
<div ng-app="myApp">
<h2>Tabs:</h2>
<div class="tabs" ng-init="selected=1">
Purchases
Products on sale
Last 30 days sales
</div>
<h2>Filters:</h2>
<div>
<label for="fromDate">From date:</label> <input type="text" name="fromDate" value="from date..." ng-model="dateFrom" datepicker />
</div>
<div>
<label for="toDate">To date:</label> <input type="text" name="toDate" value="to date..." ng-model="dateTo" datepicker />
</div>
<div class="selected" ng-controller="PurchasesCtrl" ng:show="selected == 1">
<h3>Purchases:</h3>
<table cellspacing="0">
<tr class="first">
<th class="first">Date</th>
<th>Description</th>
</tr>
<tr ng-repeat="purchase in purchases.data" ng-class-odd="'odd'" ng-class-even="'even'" ng-class="{'last':$last}">
<td class="first">{{purchase.date}}</td>
<td>{{purchase.text}}</td>
</tr>
</table>
</div>
<div class="selected" ng-controller="SaleProductsCtrl" ng:show="selected == 2">
<h3>Sale products:</h3>
<table cellspacing="0">
<tr class="first">
<th class="first">Date</th>
<th>Description</th>
</tr>
<tr ng-repeat="saleProduct in saleProducts.data" ng-class-odd="'odd'" ng-class-even="'even'" ng-class="{'last':$last}">
<td class="first">{{saleProduct.date}}</td>
<td>{{saleProduct.text}}</td>
</tr>
</table>
</div>
<div class="selected" ng-controller="Sale30DaysCtrl" ng:show="selected == 3">
<h3>Sale 30 days:</h3>
<table cellspacing="0">
<tr class="first">
<th class="first">Date</th>
<th>Description</th>
</tr>
<tr ng-repeat="sale30Day in sale30Days.data" ng-class-odd="'odd'" ng-class-even="'even'" ng-class="{'last':$last}">
<td class="first">{{sale30Day.date}}</td>
<td>{{sale30Day.text}}</td>
</tr>
</table>
</div>
</div>
JS:
var myApp = angular.module("myApp",[]);
myApp.factory("Purchases", function(){
var Purchases = {};
Purchases.data = [
{
date: "10/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "05/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "20/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
}
];
return Purchases;
});
function PurchasesCtrl($scope, Purchases){
$scope.purchases = Purchases;
}
myApp.factory("SaleProducts", function(){
var SaleProducts = {};
SaleProducts.data = [
{
date: "10/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "28/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
}
];
return SaleProducts;
});
function SaleProductsCtrl($scope, SaleProducts){
$scope.saleProducts = SaleProducts;
}
myApp.factory("Sale30Days", function(){
var Sale30Days = {};
Sale30Days.data = [
{
date: "06/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "08/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "21/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
},
{
date: "20/05/2012",
text: "Lorem ipsum dolor sit amet ipsum dolor"
}
];
return Sale30Days;
});
function Sale30DaysCtrl($scope, Sale30Days){
$scope.sale30Days = Sale30Days;
}
myApp.directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
$(function () {
element.datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function (date) {
ngModelCtrl.$setViewValue(date);
scope.$apply();
}
});
});
}
}
});
Can anyone set me on the right track with this please? I've tried everything I can think of but I've reached my AngularJS limit!
EDIT:
I've simplified the example just to try to get the basic date filtering working, so I can then get the tabs etc hooked up afterwards. Here's a simplified fiddle:
SIMPLIFIED FIDDLE: http://jsfiddle.net/bY3YL/1/
Well, your problem was quite simple, your input was outside of you controller, so even though you would had used ng-change, it would had never been called.
I fixed your code here. I also added the filtering function; it's only for the From Date input field, but I think you might figure the To Date one by yourself.
$scope.onChangeFromDate = function() {
var fromDate = $.datepicker.parseDate('dd/mm/yy', $scope.dateFrom);
angular.forEach($scope.purchases.data, function(purchase){
var purchaseDate = $.datepicker.parseDate('dd/mm/yy', purchase.date);
if(purchaseDate.getTime() < fromDate.getTime()) {
purchase.filtered = true;
}
})
}

Resources