Vuejs Search filter - javascript

I have a table that is presenting a list of items that I got using the following code:
interface getResources {
title: string;
category: string;
uri: string;
icon: string;
}
#Component
export default class uservalues extends Vue {
resources: getResources[] = [];
created() {
fetch('api/Resources/GetResources')
.then(response => response.json() as Promise<getResources[]>)
.then(data => {
this.resources = data;
});
}
}
}
And this is my table:
<div class="panel panel-default">
<div class="panel-heading" style="font-weight:bold"><span class="glyphicon glyphicon-align-justify"></span> All Resources</div>
<div class="row">
<div class="search-wrapper panel-heading col-sm-12">
<input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
</div>
</div>
<div class="panel-body" style="max-height: 400px;overflow-y: scroll;">
<table v-if="resources.length" class="table">
<thead>
<tr>
<th>Resource</th>
</tr>
</thead>
<tbody>
<tr v-for="item in resources">
<td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
I'm trying to implement a Search bar that filters the results for the user but I'm lost!
Any suggestions?

You can use the includes() function of the array to search any position in a sentence or phrase.
new Vue({
el: '#app',
data() {
return {
searchQuery: null,
resources:[
{title:"ABE Attendance",uri:"aaaa.com",category:"a",icon:null},
{title:"Accounting Services",uri:"aaaa.com",category:"a",icon:null},
{title:"Administration",uri:"aaaa.com",category:"a",icon:null},
{title:"Advanced Student Lookup",uri:"bbbb.com",category:"b",icon:null},
{title:"Art & Sciences",uri:"bbbb.com",category:"b",icon:null},
{title:"Auxiliares Services",uri:"bbbb.com",category:"b",icon:null},
{title:"Basic Skills",uri:"cccc.com",category:"c",icon:null},
{title:"Board of Trustees",uri:"dddd.com",category:"d",icon:null}
]
};
},
computed: {
resultQuery(){
if(this.searchQuery){
return this.resources.filter((item)=>{
return this.searchQuery.toLowerCase().split(' ').every(v => item.title.toLowerCase().includes(v))
})
}else{
return this.resources;
}
}
}
})
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >
</head>
<body>
<div id="app">
<div class="panel panel-default">
<div class="panel-heading">
<strong> All Resources</strong></div>
<div class="row">
<div class="search-wrapper panel-heading col-sm-12">
<input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
</div>
</div>
<div class="table-responsive">
<table v-if="resources.length" class="table">
<thead>
<tr>
<th>Resource</th>
</tr>
</thead>
<tbody>
<tr v-for="item in resultQuery">
<td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Based on this answer → Vue.js search keyword in array

You could use computed property for this case, so, i created one called filteredResources which will be used in v-for loop, i had used dummy data, but you could keep your resources declared empty and call a promise function to fill it in created hook, check this code if your are preferring single file component or the following code of you're using Vue via CDN
new Vue({
el: '#app',
data() {
return {
searchQuery:'',
resources:[
{title:"aaa",uri:"aaaa.com",category:"a",icon:null},
{title:"add",uri:"aaaa.com",category:"a",icon:null},
{title:"aff",uri:"aaaa.com",category:"a",icon:null},
{title:"bbb",uri:"bbbb.com",category:"b",icon:null},
{title:"bdd",uri:"bbbb.com",category:"b",icon:null},
{title:"bsb",uri:"bbbb.com",category:"b",icon:null},
{title:"ccc",uri:"cccc.com",category:"c",icon:null},
{title:"ddd",uri:"dddd.com",category:"d",icon:null}
]
};
},
computed: {
filteredResources (){
if(this.searchQuery){
return this.resources.filter((item)=>{
return item.title.startsWith(this.searchQuery);
})
}else{
return this.resources;
}
}
}
})
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >
</head>
<body>
<div id="app">
<div class="panel panel-default">
<div class="panel-heading" style="font-weight:bold"><span class="glyphicon glyphicon-align-justify"></span> All Resources</div>
<div class="row">
<div class="search-wrapper panel-heading col-sm-12">
<input class="form-control" type="text" v-model="searchQuery" placeholder="Search" />
</div>
</div>
<div class="panel-body" style="max-height: 400px;overflow-y: scroll;">
<table v-if="resources.length" class="table">
<thead>
<tr>
<th>Resource</th>
</tr>
</thead>
<tbody>
<tr v-for="item in filteredResources">
<td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

Here is Vue 3 version of a simple search.
const { createApp, ref } = Vue
const App = {
setup() {
let searchText = ref('')
const list = [
'orange',
'red',
'blue',
'black',
'white'
]
function filteredList() {
return list.filter(data => data.toLowerCase().includes(searchText.value.toLowerCase()))
}
return {searchText, filteredList}
}
}
Vue.createApp(App).mount('#app')
<script src="https://unpkg.com/vue#next"></script>
<div id="app">
<input type="text" v-model="searchText">
<ul>
<li v-for="data in filteredList()" :key="data">
{{ data }}
</li>
</ul>
</div>

THIS NAVBAR COMPONENTS
<template>
<nav class="navbar navbar-expand-lg navbar-light bg-info display-6">
<div class="container">
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<form class="d-flex">
<input v-model="search" class="form-control me-2" id="inputGroup-sizing-lg" placeholder="Search...">
</form>
</div>
</div>
</nav>
</template>
<script>
import {mapActions} from "vuex"
export default{
data(){
return{
search: ""
}
},
watch:{
search(newsearch) {
this.filteredProducts(newsearch)
}
},
methods:{
...mapActions([
"filteredProducts"
])
}
}
</script>
THIS STORE.JS
const store = createStore({
state: {
productsList: products,
cartList: [],
filtered: []
},
mutations:{
filteredProducts(state, item) {
if(item){
state.filtered = products.filter((product) => product.Title.toUpperCase().includes(item.toUpperCase()))
console.log(state.filtered);
}
if(state.filtered){
console.log("state.filtered.lenght", state.filtered.lenght);
state.productsList = [...state.filtered]
}
}
},
actions:{
filteredProducts (context, item){
context.commit('filteredProducts', item)
}
}
});

I found easy way...using "#input function".. It's work for me!
new Vue({
el: '#app',
data() {
return {
searchQuery:'',
resources:[
{title:"aaa",uri:"aaaa.com",category:"a",icon:null},
{title:"add",uri:"aaaa.com",category:"a",icon:null},
{title:"aff",uri:"aaaa.com",category:"a",icon:null},
{title:"bbb",uri:"bbbb.com",category:"b",icon:null},
{title:"bdd",uri:"bbbb.com",category:"b",icon:null},
]
};
},
methods: {
getTextSearch: function(textSearch) {
this.filteredResources= this.resources
this.filteredResources= this.filteredResources.filter(item => {
return item.uri.toLowerCase().includes(textSearch);
});
},
}
})
Here html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" >
</head>
<body>
<div id="app">
<div class="panel panel-default">
<div class="panel-heading" style="font-weight:bold"><span class="glyphicon glyphicon-align-justify"></span> All Resources</div>
<div class="row">
<div class="search-wrapper panel-heading col-sm-12">
<input class="form-control" #input="getTextSearch($event)" type="text" placeholder="Search" />
</div>
</div>
<div class="panel-body" style="max-height: 400px;overflow-y: scroll;">
<table v-if="resources.length" class="table">
<thead>
<tr>
<th>Resource</th>
</tr>
</thead>
<tbody>
<tr v-for="item in filteredResources">
<td><a v-bind:href="item.uri" target="_blank">{{item.title}}</a></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

Related

can't search fetched data from html table

I have some code (as below) HTML and JavaScript . Actually, I've already fetched some of data from a covid-19 API and also i kept those information on HTML table .
So, now i wanna search info from the HTML table with country name. But, I couldn't that. So, please some one help me to solve this problem .
fetch('https://api.covid19api.com/summary')
.then(response => response.json())
.then(data => {
var tbody = document.querySelector('#tbody');
tbody.innerHTML = `
<tr>
<td>${data.Global.NewConfirmed}</td>
<td>${data.Global.TotalConfirmed}</td>
<td>${data.Global.TotalDeaths}</td>
<td>${data.Global.TotalRecovered}</td>
</tr>
`
var all_covid_data = document.querySelector('#all_covid_data')
var countries = data.Countries ;
for(var i =1;i<countries.length ; i++){
all_covid_data.innerHTML += ` <tr>
<td class='bg-primary text-light '>${countries[i].Country}</td>
<td>${countries[i].NewConfirmed}</td>
<td>${countries[i].NewDeaths}</td>
<td>${countries[i].NewRecovered}</td>
<td>${countries[i].TotalConfirmed }</td>
<td>${countries[i].TotalRecovered}</td>
<td>${countries[i].TotalDeaths}</td>
</tr>`;
}
})
.catch(err => console.log(err))
// searching or filtering data from table
var tableRow = document.getElementById('all_covid_data');
var inputField = document.getElementById('searchBox');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="./style.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Covid-19 Info</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 py-3">
<h2 class="text-uppercase text-center">Covid-19 Informations</h2>
<hr style="width: 110px; text-align: center; border-width: 3px; border-color:#17A2B8">
<table class="table">
<thead class="bg-info text-light">
<tr>
<th>NewConfirmed</th>
<th>TotalCases</th>
<th>TotalDeaths</th>
<th>TotalRecovered</th>
</tr>
</thead>
<tbody class="bg-dark text-light" id='tbody'>
</tbody>
</table>
</div>
<div class="col-md-2"></div>
</div>
<section id="countries_data" class="py-4">
<div class="row">
<div class="col-12">
<div class="d-flex">
<input type="text" name="" placeholder="Search here" id="searchBox" class="form-control">
<button class="btn ml-2 btn-info">Search</button>
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped my-4 table-hover">
<thead class="bg-info text-light">
<tr>
<th>Countries</th>
<th>NewConfirmed</th>
<th>NewDeaths</th>
<th>NewRecovered</th>
<th>TotalConfirmed</th>
<th>TotalRecovered</th>
<th>TotalDeaths</th>
</tr>
</thead>
<tbody id='all_covid_data'>
</tbody>
</table>
</div>
</section>
</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="./app.js"></script>
</body>
</html>
Create separate methods, one to fetch data from API & another to populate the table.
Simply use filter() method to filter Country by name and re-use the populateTable() method.
Start the for loop from 0.
$(document).ready(function() {
var summary;
fetch('https://api.covid19api.com/summary')
.then(response => response.json())
.then(data => {
summary = data;
populateTable(data);
})
.catch(err => console.log(err))
function populateTable(data) {
var tbody = document.querySelector('#tbody');
tbody.innerHTML = `
<tr>
<td>${data.Global.NewConfirmed}</td>
<td>${data.Global.TotalConfirmed}</td>
<td>${data.Global.TotalDeaths}</td>
<td>${data.Global.TotalRecovered}</td>
</tr>
`;
var countries = data.Countries;
let content = '';
for (var i = 0; i < countries.length; i++) {
content += `<tr>
<td class='bg-primary text-light '>${countries[i].Country}</td>
<td>${countries[i].NewConfirmed}</td>
<td>${countries[i].NewDeaths}</td>
<td>${countries[i].NewRecovered}</td>
<td>${countries[i].TotalConfirmed }</td>
<td>${countries[i].TotalRecovered}</td>
<td>${countries[i].TotalDeaths}</td>
</tr>`;
}
$('#all_covid_data').html(content);
}
// searching or filtering data from table
var tableRow = document.getElementById('all_covid_data');
var inputField = document.getElementById('searchBox');
$("#search_btn").click(() => {
var filteredData = JSON.parse(JSON.stringify(summary));
filteredData.Countries = filteredData.Countries.filter(c => c.Country.toLowerCase().includes(inputField.value.toLowerCase()));
if (filteredData.Countries.length > 0) {
$('#all_covid_data').html('');
populateTable(filteredData);
} else {
alert('Country not found');
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="./favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="./style.css">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Covid-19 Info</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8 py-3">
<h2 class="text-uppercase text-center">Covid-19 Informations</h2>
<hr style="width: 110px; text-align: center; border-width: 3px; border-color:#17A2B8">
<table class="table">
<thead class="bg-info text-light">
<tr>
<th>NewConfirmed</th>
<th>TotalCases</th>
<th>TotalDeaths</th>
<th>TotalRecovered</th>
</tr>
</thead>
<tbody class="bg-dark text-light" id='tbody'>
</tbody>
</table>
</div>
<div class="col-md-2"></div>
</div>
<section id="countries_data" class="py-4">
<div class="row">
<div class="col-12">
<div class="d-flex">
<input type="text" name="" placeholder="Search here" id="searchBox" class="form-control">
<button class="btn ml-2 btn-info" id="search_btn">Search</button>
</div>
</div>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped my-4 table-hover">
<thead class="bg-info text-light">
<tr>
<th>Countries</th>
<th>NewConfirmed</th>
<th>NewDeaths</th>
<th>NewRecovered</th>
<th>TotalConfirmed</th>
<th>TotalRecovered</th>
<th>TotalDeaths</th>
</tr>
</thead>
<tbody id='all_covid_data'>
</tbody>
</table>
</div>
</section>
</div>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="./app.js"></script>
</body>
</html>

PrimeNg ConfirmDialog design messed up, CSS not applying

Template :
<p-confirmDialog header="Confirmation" icon="fa fa-question-circle" appendTo="body" responsive="true"></p-confirmDialog>
<button type="button" class="btn btn-primary" (click)="confirm()" >Save</button>
Component:
confirm() {
console.log('confirm?');
this.confirmationService.confirm({
message: 'Are you sure that you want to update?',
accept: () => {
console.log('update clicked');
}
});
}
Output display:
Is there any css file etc that I need to include?
Template(full):
<!---------------- Meta and Title ---------------->
<meta charset="utf-8">
<title>Solid Waste Management System</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<div class="tables-basic" data-spy="scroll" data-target="#nav-spy" data-offset="300">
<!-- -------------- Body Wrap -------------- -->
<div id="main">
<p-confirmDialog header="Confirmation" icon="fa fa-question-circle" appendTo="body" responsive="true"></p-confirmDialog>
<!-- -------------- Topbar -------------- -->
<header id="topbar" class="alt">
<div class="topbar-left">
<ol class="breadcrumb">
<li class="breadcrumb-icon">
<a href="#">
<span class="fa fa-eye"></span>
</a>
</li>
<li class="breadcrumb-active">
Organizational User
</li>
</ol>
</div>
<div class="topbar-right">
<a class="btn btn-primary btn-sm" href="Edit.html">
<i class="fa fa-edit"></i> Edit
</a>
<a class="btn btn-dark btn-sm" href="UserList.html">
<i class="fa fa-arrow-left"></i> Back
</a>
</div>
</header>
<!-- -------------- /Topbar -------------- -->
<!-- -------------- Content -------------- -->
<section id="content" class="table-layout animated fadeIn">
<!-- -------------- Column Center -------------- -->
<div class="chute chute-center">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-visible p10">
<div class="panel-body pn mn allcp-form theme-primary">
<form id="form-order" (ngSubmit)="onSubmit(f)" #f="ngForm">
<h6>OrgUser</h6>
<div class="section row ">
</div>
<!-- -------------- /section -------------- -->
<div class="section row">
<div class="col-md-6 ph10 mb5">
<label for="userid">User ID: </label>
<p-autoComplete (ngModelChange)="orguser.userid = $event" class="ui-autocomplete autocomplete" [suggestions]="results" (completeMethod)="search($event)"
(onSelect)="onSelect($event)" (onBlur)="onBlur($event.target.value)" field="userid"></p-autoComplete>
<input type="hidden" name="userid" [ngModel]="orguser?.userid">
</div>
<div class="col-md-6 ph10 mb5">
<label for="perid">Personnel ID:</label>
<input type="text" class="form-control" [ngModel]="orguser?.perid" (ngModelChange)="orguser.perid = $event" name="perid"
id="perid">
</div>
</div>
<div class="section row">
<div class="col-md-6 ph10 mb5">
<label for="Password">Password:</label>
<input type="text" class="form-control" [ngModel]="orguser?.password" (ngModelChange)="orguser.password = $event" name="password"
id="password">
</div>
<div class="col-md-6 ph10 mb5">
<label for="fullname">Name:</label>
<input type="text" class="form-control" name="fullname" disabled [ngModel]="orguser?.perfullname" (ngModelChange)="orguser.perfullname = $event"
id="fullname">
</div>
</div>
<div class="section row">
<div class="col-md-6 ph10 mb5">
<label for="type">CreatedOn:</label>
<input type="text" class="form-control" name="createdon" disabled [ngModel]="orguser?.createdon" (ngModelChange)="orguser.createdon = $event"
id="createdon">
</div>
<div class="col-md-6 ph10 mb5 ">
<label for="CreatedBy ">CreatedBy:</label>
<input type="text" class="form-control" name="createdby" disabled [ngModel]="orguser?.createdby" (ngModelChange)="orguser.createdby = $event"
[(ngModel)]="orguser.createdby" id="createdby">
</div>
</div>
<div class="section row">
<div class="col-md-6 ph10 mb5">
<label for="Deletedby">Deleted By:</label>
<input type="text" class="form-control" disabled name="Deletedby" id="Deletedby">
<div class="col-md-6 ph10 mb5">
<label for="isactive">IsActive:</label>
<input type="checkbox" id="isactive" [ngModel]="orguser?.isactive" (ngModelChange)="orguser.isactive = $event" name="isactive">
</div>
</div>
<div class="section row">
<div class="col-md-6 ph10 mb5">
<label for="isdeleted">Is Deleted:</label>
<input type="checkbox" id="isdeleted" [ngModel]="orguser?.isdeleted" (ngModelChange)="orguser.isdeleted = $event" name="isdeleted">
</div>
</div>
</div>
<!-- -------------- /section -------------- -->
<hr>
<!-- -------------- /section -------------- -->
<div class="section text-right mb10 ">
<button type="button" class="btn btn-primary" (click)="confirm()">Save</button>
</div>
<!-- -------------- /Panel Body -------------- -->
</form>
</div>
</div>
</div>
</div>
</div>
<!-- -------------- /Column Center -------------- -->
</section>
<!-- -------------- /Content -------------- -->
</div>
</div>
Componenet(full):
import { Component, OnInit, ViewChild } from '#angular/core';
import { orguser } from '../../Models/orguser';
import { PersonnelService } from '../../services/personnel.service';
import { OrguserService } from '../../services/orguser.service';
import {ConfirmDialogModule} from 'primeng/confirmdialog';
import {ConfirmationService} from 'primeng/api';
#Component({
selector: 'app-orguseraddedit',
templateUrl: './orguseraddedit.component.html',
styleUrls: ['./orguseraddedit.component.css'],
})
export class OrguseraddeditComponent implements OnInit {
orguser: orguser = new orguser();
val: any;
results: any[];
constructor(private _PersonnelService: PersonnelService, private _OrguserService: OrguserService,private confirmationService: ConfirmationService) {
}
confirm() {
console.log('confirm?');
this.confirmationService.confirm({
message: 'Are you sure that you want to update?',
accept: () => {
console.log('update clicked');
}
});
}
confirm1() {
this.confirmationService.confirm({
message: 'Are you sure that you want to Add?',
accept: () => {
console.log('add clicked');
},
key:"add"
});
}
search(event) {
this._OrguserService.GetOrgUsersForAutocomplete(event.query)
.subscribe((userdata: any[]) => { this.results = userdata;console.log('xxxx'); console.log(this.results); }, (error) => {
//this.statusMessage = 'Problem with service. Please try again.'
console.error(error);
});
}
handleDropdown(event) {
console.log(event.query);
//event.query = current value in input field
}
ngOnInit() {
//this.orguser=null;
}
onBlur(value){
this._OrguserService.selectOrgUsersById(value)
.subscribe((userdata: any[]) => { this.orguser = userdata[0]; }, (error) => {
console.error(error);
});
}
onSelect(value) {
this.getuser(value.userid);
}
getuser(value){
this._OrguserService.selectOrgUsersById(value)
.subscribe((userdata: any[]) => { this.orguser = userdata[0]; console.log(this.orguser); }, (error) => {
console.error(error);
});
}
onSubmit(f) {
this._OrguserService.addupdateOrguser(f.value)
.subscribe((res: any) => {
console.log(res);
this.orguser = res;
{ console.log('success'); this.getuser(f.value.userid); };
}, (error) => {
console.error(error);
});
}
}
interface IAutoCompleteItem {
value: any;
text: string;
markup?: string;
isFocus?: boolean;
}
After removing all the stylesheet references and everything else on the template this is what I am getting:
I am not sure what you exactly wrong. But I'Ll give the proper way to use primeng confirm dialog box. You can get what you missing from that
First you need import ConfirmationService from primeng package
import { ConfirmationService} from 'primeng/primeng';
Then you should inject this via constructor like
constructor(private confirmationService: ConfirmationService) { }
And use the below code while open confirmation dialog box
this.confirmationService.confirm({
message: 'Are you sure to delete this?',
icon: 'fa fa-question-circle',
header: 'Delete Confirmation',
accept: () => {
// do accept criteria
}
},
reject: () => {
//close the dialogue
}
});
And the HTML code Could be
<p-confirmDialog width="500"></p-confirmDialog>
EDIT
While looking your code, You are missing to assign any value for Confirmation object in header="Confirmation".So please remove header="Confirmation" and add that in confirmationservice parameter. also remove appendTo="body". Please try this and let me know
Finally, I have figured out what I was missing.
<link rel="stylesheet" href="https://unpkg.com/primeng#4.1.0/resources/themes/omega/theme.css" />
<link rel="stylesheet" href="https://unpkg.com/primeng#4.1.0/resources/primeng.min.css" />
Since I am new to angular I am not sure about the correct way to reference the local files in node_modules so I have used cdn.
It working.

Vue doesn't render content in my component's mustache templates ( {{}} )

I'm already banging my head against this problem the whole day. Following problem, that my mustache bracer components don't get rendered on my site. I just get the unrendered components in bracers as output.
//app.js
//
import Vue from 'vue'
new Vue({
//We want to target the div with an id of 'events'
el: '#events',
//Here we can register any values or collections that hold data
//for the application
data: {
event: {
name: '',
description: '',
date: ''
},
events: []
},
// Anything within the ready function will run when the application loads
ready: function() {
//When application loads, we want to call the method that initializies
//some data
this.fetchEvents();
},
// Methods we want to use in our application are registered here
methods: {
//We dedicate a method to retrieving and setting some data
fetchEvents: function() {
// body...
var events = [{
id: 1,
name: 'TIFF',
description: 'Toronto International Film Festival',
date: '2015-09-10'
},
{
id: 2,
name: 'The Martian Premiere',
description: 'The Martian comes to theatres',
date: '2015-10-02'
},
{
id: 3,
name: 'SXSW',
description: 'Music, film and interactive festival in Austin, TX'
date: '2016-03-11'
}
];
//Set is a convenience method provided by Vue that is similar to pushing
//data onto an array
this.$set('events', events);
},
//Adds an event to the existing events array
addEvent: function() {
if (this.event.name) {
this.events.push(this.event);
this.event = {
name: '',
description: '',
date: ''
};
}
}
deleteEvent: function(index) {
if (confirm("Are you sure you want to delete this Event?")) {
//$remove is a Vue convenience method similar to splice
this.events.$remove(index);
}
}
}
});
<!DOCTYPE html>
<html>
<head>
<title>Vue</title>
<meta charset="utf-8">
<!-- CSS -->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
<script src="node_modules/vue/dist/vue.js"></script>
<script src="node_modules/vue-resource/dist/vue-resource.js"></script>
<script src="app.js"></script>
</head>
<body>
<!-- navigation bar -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<a class="navbar-brand"><i class="glyphicon glyphicon-bullhorn"></i>Vue Events Bulletin</a>
</div>
</nav>
<!-- main body of our application -->
<div class="container" id="events">
<!-- add an event form -->
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Add an Event</h3>
</div>
<div class="panel-body">
<div class="form-group">
<input class="form-control" placeholder="Event Name" v-model="event.name">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Event Description" v-model="event.description"></textarea>
</div>
<div class="form-group">
<input type="date" class="form-control" placeholder="Date" v-model="event.date">
</div>
<button class="btn btn-primary" v-on:click="addEvent()">Submit</button>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="list-group">
<a href="#" class="list-group-item" v-repeat="event in events">
<h4 class="list-group-item-heading">
<i class="glyphicon glyphicon-bullhorn"></i> {{ event.name }}
</h4>
<h5>
<i class="glyphicon glyphicon-calender" v-if="event.date"></i> {{ event.date }}
</h5>
<p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>
<button class="btn btn-xs btn-danger" v-on:click="deleteEvent($index)">Delete</button>
</a>
</div>
</div>
</div>
<!-- JS -->
<!--<script src="node_modules/vue/dist/vue.js"></script> -->
<!--<script src="node_modules/vue-resource/dist/vue-resource.js"><!--</script> -->
<!--<script src="app.js"></script> -->
</body>
I was able to get the App running! This is the working Code in case someone struggles with something similar!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bulletin Board</title>
<meta charset="utf-8">
<!-- <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui"> -->
<!-- <meta name="apple-mobile-web-app-capable" content="yes">-->
<!-- <meta name="apple-mobile-web-app-status-bar-style" content="black"> -->
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<a class="navbar-brand"><i class="glyphicon glyphicon-bullhorn"></i>Vue Events Bulletin</a>
</div>
</nav>
<!-- main body of our application -->
<div class="container" id="app">
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Add an Event</h3>
</div>
<div class="panel-body">
<div class="form-group">
<input class="form-control" placeholder="Event Name" v-model="event.name">
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Event Description" v-model="event.description"></textarea>
</div>
<div class="form-group">
<input type="date" class="form-control" placeholder="Date" v-model="event.date">
</div>
<button class="btn btn-primary" v-on:click="addEvent()">Submit</button>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="list-group">
<a href="#" class="list-group-item" v-for="event in events">
<h4 class="list-group-item-heading">
<i class="glyphicon glyphicon-bullhorn"></i>
{{ event.name }}
</h4>
<h5>
<i class="glyphicon glyphicon-calender" v-if="event.date"></i>
{{ event.date }}
</h5>
<p class="list-group-item-text" v-if="event.description">{{ event.description }}</p>
<button class="btn btn-xs btn-danger" v-on:click="deleteEvent($index)">Delete</button>
</a>
</div>
</div>
<script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="node_modules/vue/dist/vue.js"></script>
<script src="node_modules/vue-resource/dist/vue-resource.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
And the app.js
new Vue({
el: '#app',
data: {
event: {
name: '',
description: '',
date: ''
},
events: []
},
mounted: function() {
//alert('mounted')
this.fetchEvents();
},
methods: {
fetchEvents: function() {
var events = [{
id: 1,
name: 'TIFF',
description: 'Toronto International Film Festival',
date: '2015-09-10'
},
{
id: 2,
name: 'The Martian Premiere',
description: 'The Martian comes to theatres',
date: '2015-10-02'
},
{
id: 3,
name: 'SXSW',
description: 'Music, film and interactive festival in Austin, TX',
date: '2016-03-11'
}
];
this.events = events;
},
//Adds an event to the existing events array
addEvent: function() {
if (this.event.name) {
this.events.push(this.event);
this.event = {
name: '',
description: '',
date: ''
};
}
},
deleteEvent: function (index) {
if (confirm('Are you sure you want to delete this event?')) {
this.events.splice(index, 1);
}
// body...
}
}
});

Vue.js 2.x v-for in a <table> not working (Property or method not defined)

I was trying to iterate though an array defined in the data section of a Vue instance, so the table head could be determined automatically. But when I ran the code, the console output was as follows:
Here's the code (.js file combined):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Demo</title>
<link href="http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
<script src="http://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<h3>
Staffs
</h3>
<table id="mytable" class="table table-hover">
<thead>
<tr>
<th v-for:"term in items">
{{term}}
</th>
</tr>
</thead>
<tbody>
<tr>
<td>6556</td>
<td>
TB - Monthly
</td>
<td>
01/04/2012
</td>
<td>
Default
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row clearfix">
<div class="col-md-8 column">
<ul class="pagination">
<li>
Prev
</li>
<li v-for="n in 5">
{{n}}
</li>
<li>
Next
</li>
</ul>
</div>
<div class="col-md-4 column">
<button class="btn btn-default" type="button">button</button>
</div>
</div>
</div>
<script>
'use strict';
console.log("here we go!");
var tab = new Vue({
el: '#mytable',
data: {
items: ['aa','bb']
}
});
</script>
</body>
</html>
And the appearance was like:
Replace
v-for:"term in items"
With
v-for="term in items"

knockoutjs can not apply bindings multiple times to the same element

in following code uncaught error is found..
the binding is applied only once till it display can not apply bindings multiple times...
is it problem of knockout version ?
can be write following code in a immediatly invoke function...
var DummyContact = [
{
"ContactID": 1,
"FirstName": "Nimesh",
"LastName": "Vaghasiya"
},
{
"ContactID": 2,
"FirstName": "John",
"LastName": "Cena"
}
];
var ContactViewModel = function () {
var self = this;
var url = "/Contacts/GetAllContacts";
//var refresh = function () {
// $.getJSON(url, {}, function (data) {
// self.Contacts(data);
// });
//};
var refresh = function () {
self.Contacts(DummyContact);
};
// public data properties
self.Contacts = ko.observableArray([]);
refresh();
self.createContact = function () {
window.location.href = '/Contacts/CreateEdit/0';
};
self.editContact = function (Contact) {
window.location.href = '/Contacts/CreateEdit/' + Contact.ContactID;
};
self.removeContact = function (Contact) {
if (confirm("Are you sure you want to delete this profile?")) {
self.Contacts.remove(Contact);
}
};
};
ko.applyBindings(new ContactViewModel());
html code is :
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<html>
<body>
<input type="button" class="btn btn-small btn-primary" value="New Contact" data-bind="click:$root.createContact" />
<hr />
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th></th>
</tr>
<tbody data-bind="foreach: Contacts">
<tr>
<td class="name"><a data-bind="text: FirstName, click:$parent.editContact"></a></td>
<td data-bind="text: LastName"></td>
<td>
<button class="btn btn-mini btn-danger" data-bind="click:$parent.removeContact">remove</button></td>
</tr>
</tbody>
</table>
</body>
</html>
<script src="~/Scripts/Contact.js"></script>
//layout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title - My ASP.NET MVC Application</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/themes/base/jquery.ui.all.css")
#Styles.Render("~/Content/themes/base/jquery.ui.dialog.css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/knockout")
</head>
<body>
<header>
<div class="container content-wrapper">
<div class="float-left">
<p class="site-title">
<a href="#Url.Action("Index", "Home")">
<img src="~/Content/themes/base/images/address-book.png" style="margin-left: -5px" /></a>
</p>
</div>
<div class="float-right">
<section id="login">
#Html.Partial("_LoginPartial")
</section>
<nav>
<ul id="menu">
<li>#Html.ActionLink("Home", "Index", "Home")</li>
#if (Request.IsAuthenticated)
{
<li>#Html.ActionLink("Groups", "Index", "Groups")</li>
<li>#Html.ActionLink("Contacts", "Index1", "Contacts")</li>
<li>#Html.ActionLink("Address", "Index", "Address")</li>
<li>#Html.ActionLink("Email", "Index", "Emails")</li>
<li>#Html.ActionLink("Numbers", "Index", "Numbers")</li>
}
<li>#Html.ActionLink("Contact Us", "Contact", "Home")</li>
<li>#Html.ActionLink("About", "About", "Home")</li>
</ul>
</nav>
</div>
</div>
</header>
<div id="body">
#RenderSection("featured", required: false)
<section class="content-wrapper main-content clear-fix container">
#RenderBody()
</section>
</div>
<footer>
<div class="content-wrapper container">
<div class="float-left">
<p>© #DateTime.Now.Year - My ASP.NET MVC Application</p>
</div>
</div>
</footer>
#Scripts.Render("~/bundles/jquery")
#Styles.Render("~/Content/bootstrap/bootstrap.css")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/modaldialog.js")
#RenderSection("scripts", required: false)
</body>
<script type="text/javascript">
(function () {
$("#body").show({ effect: "drop", direction: "down", distance: 200, duration: 1000 })
})();
</script>
</html>
Change your html so something like this:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<html>
<body>
<div id="unique-view-data">
<input type="button" class="btn btn-small btn-primary" value="New Contact" data-bind="click:$root.createContact" />
<hr />
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th></th>
</tr>
<tbody data-bind="foreach: Contacts">
<tr>
<td class="name"><a data-bind="text: FirstName, click:$parent.editContact"></a></td>
<td data-bind="text: LastName"></td>
<td>
<button class="btn btn-mini btn-danger" data-bind="click:$parent.removeContact">remove</button></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
<script src="~/Scripts/Contact.js"></script>
And change the last line in your javascript to this:
ko.applyBindings(new ContactViewModel(), document.getElementById("unique-view-data"));
This tells knockout to only apply the bindings to the DOM element specified in the second parameter.
I suspect that there might be other viewmodels also trying to apply bindings. If that is the case, please update the other viewmodels appropriately.

Categories