I can get the elements sent from the backend.But the text can't display.I don't know why.
here is my html :
<!-- <form action=""> -->
<div class=" form-group">
<input v-model="wd" #keyup="keyup($event)" type="text" class="form-control" />
<!-- <ul class="list-group"> -->
<table>
<tr>
<th v-for="item in title"><div style="width:500px">{{item}}</div> </th>
</tr>
<tr v-for="item in arr" :key='item'>
<td>{{item.name}}</td>
<td>{{item.sort}}</td>
<td>{{item.company}}</td>
</tr>
</table>
</div>
here is My Vue:
el: "#app",
data: {
wd: '',
arr: [],
listIndex: -1,
title:['name','sort','company'],
},
methods: {
keyup(event) {
var url = "/search/search/"
axios.get(url, {
params: {
q: this.wd,
}
}).then(res => {
console.log(res);
this.arr = res.data.list;
})
}
}
})
;
I know the data was got.Because the number of the items in loop is exactly correct.When I console.log(res.data.list),I can view the data from the backend.But they can't display in my page.
I will be very appreciate it if you could help me.Thank you!
enter image description here
I think the problem is in your reference to this.arr in your callback. When the AJAX call returns, this is scoped to the response, not your Vue object.
You can overcome this by inserting a variable prior to the AJAX call, like this:
var vm = this;
axios.get(url, {
then, in the callback, instead of this.arr = res.data.list;, do this:
vm.arr = res.data.list;
The field data must be reactive
data() {
return{
wd: '',
arr: [],
listIndex: -1,
title:['name','sort','company'],
}
}
Related
I have this code and I get an array in the info variable. The problem is in the delete button that calls the remove function passing the id as a parameter but it passes the first id to all elements so when I delete any element it deletes the first one instead of referring to the button
<tr>
<th scope="row">{{info.product_key}}</th>
<td>{{info.name}}</td>
<td>{{info.quantities}}</td>
<td>{{info.quatities_sold}}</td>
<td>{{info.cost_price}}</td>
<td>{{info.sale_price}}</td>
<td><button #click="showEditModal" class="btn btn-warning">editar</button></td>
<EditProductModal
:_id=info._id
:product_key=info.product_key
:product_name=info.name
:quantities=info.quantities
:quantities_sold=info.quatities_sold
:cost_price=info.cost_price
:sale_price=info.sale_price
:categories=info.categories
/>
<td><button #click="remove(info._id)" class="btn btn-danger">excluir</button></td>
</tr>
</tbody>```
As you said I get an array in the info variable but looks like instead of iterating you are directly using it. If you are iterating it properly using v-for it should pass the correct ID.
Working Demo :
const app = new Vue({
el: '#app',
data: {
info: [{
'_id': 1,
'name': 'alpha'
}, {
'_id': 2,
'name': 'beta'
}, {
'_id': 3,
'name': 'gama'
}]
},
methods: {
remove(itemID) {
console.log(itemID);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<table>
<tr v-for="item in info" :key="item._id">
<td>{{item.name}}</td>
<td><button #click="remove(item._id)">excluir</button></td>
</tr>
</table>
</div>
I'm making a vue.js front-end feature that could filter data by keywords and sort data in either ascending or descending order. And I found this code online which might meet my requirements. However the format of its data array is different from my retrieved array:
<template>
<div id="app">
<br /><br />
<div>
<input type="text" v-model="filterValue" placeholder="Filter">
<button #click="invertSort()">Sort asc/desc</button>
</div>
<table class="table table-striped">
<thead>
<tr>
<td>Name</td>
<td>Value</td>
</tr>
</thead>
<tbody>
<tr v-for="data in filteredAndSortedData">
<td>{{data.name}}</td>
<td>{{data.val}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
testData: [{name:'3', val:'a'}, {name:'2', val:'b'}, {name:'1', val:'c'}, {name:'4', val:'d'}],
error: "",
errorFlag: false,
filterValue: "",
sortAsc: true
};
},
computed: {
filteredAndSortedData() {
// Apply filter first
let result = this.testData;
if (this.filterValue) {
result = result.filter(item => item.name.includes(this.filterValue));
}
// Sort the remaining values
let ascDesc = this.sortAsc ? 1 : -1;
return result.sort((a, b) => ascDesc * a.name.localeCompare(b.name));
}
},
methods: {
invertSort() {
this.sortAsc = !this.sortAsc;
}
},
}
</script>
So in the provided function its array is like testData: [{name:'1', val:'a'}], however, my array which retrieved by using this.testData = response.data in function(response) is like testData: [{"name":"1", "val":"a"}]
That being said, my variable names are double-quoted and cannot use the code I want. Is there a way to convert [{"name":"1", "val":"a"}] to [{name:'1', val:'a'}] (like removing variable names quotes) or sort it without modifying the array?
you can get object key sting using
var a = [{"name":"1", "val":"a"}];
console.log(a[0]["name"])
// if you already know key
console.log(a[0].name)
and this [{"name":"1", "val":"a"}] and [{name:'1', val:'a'}] is same in javascript.
I want to disable button Assign when it clicked, bacause it should assign only once so i can achieve this, I have done the following code in HTML:
<table class="table details">
<thead>
<tr>
<th sort-by="firstName">User Name</th>
<th sort-by="lastName">Description</th>
<th sort-by="Budget" sort-init="desc">Bid Amount</th>
<th sort-by="lastName">Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="issue in issues | filter:filter">
<td><strong><a href="/ViewBid/Index?{{ issue.User_ID }}" />{{ issue.UserName }} </strong></td>
<td><a href="/ViewBid/Index?{{ issue.User_ID }}" />{{ issue.Description }}</td>
<td><a href="/ViewBid/Index?{{ issue.User_ID }}" />{{issue.Bid_amt}}</td>
<td>
<div ng-controller="ExampleCtrl_Assign">
<div ng-show="AsgHide">
<button type="button" ng-click="AssignRecord(issue.ID,issue.Description,issue.Bid_amt)">Assign</button>
</div>
</div>
<div ng-controller="ExampleCtrl_Delete">
<div ng-show="AsgHide" >
<button type="button" ng-click="DeleteRecord(issue.ID)">Delete</button>
</div>
</div>
</td>
</tr>
</tbody>
</table>
And JavaScript Code is as following:
var app = angular.module('siTableExampleApp_Assign', []);
app.controller('ExampleCtrl_Assign', ['$scope','$http', function ($scope, $http) {
var user2 = window.localStorage.getItem('UserId');
var Basic = window.localStorage.getItem('Basic');
var Token = window.localStorage.getItem('Token');
$scope.FunctionDisable = function (i) {
$("#rbutton'+i+'").attr("disabled", "disabled");
}
$scope.AssignRecord = function (ID, Description, Bid_amt) {
var BidID = ID;
var date = new Date();
encodedString = {
"ID": 1,
"Travel_Info_ID": travel_info_id,
"Bid_ID": parseInt(BidID),
"Description": Description,
"Bid_amt": Bid_amt,
"Status": "InProcess",
"User_ID": user2,
"Entry_Date": date,
"Update_Date": date
}
$http({
method: 'POST',
url: 'http://saisoftwaresolutions.com/v1/Assigned_Bids/Assigned_Bid/Create',
data: encodedString,
headers: {
'Authorization': 'Basic ' + Basic,
'Token': Token
}
})
.success(function (data, status, headers, config) {
console.log(headers());
console.log(data);
if (status === 200) {
//window.location.href = 'http://localhost:22135/BDetail/Index';
} else {
$scope.errorMsg = "Login not correct";
}
})
.error(function (data, status, headers, config) {
$scope.errorMsg = 'Unable to submit form';
})
Use can always use ng-disabled directive provided by Angular to disabled html elements.
I have made one example based on your requirements and help it will solve your issue:
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat="item in items">{{item.User_ID}}: {{item.User_Name}}
<button ng-click="handleClick($index)" ng-disabled="item.disabled">
{{item.User_Name}}
</button>
</li>
</ul>
</div>
function MyCtrl($scope) {
$scope.items = [
{
User_ID: '10',
disaled: false,
User_Name: 'ABC'
}, {
User_ID: '11',
disaled: false,
User_Name: 'XYZ'
}
];;
$scope.handleClick = function(index){
$scope.items[index].disabled = true;
}
}
Angular has a directive just for this: ng-disabled.
From their official documentation:
This directive sets the disabled attribute on the element if the
expression inside ngDisabled evaluates to truthy.
So you can set a boolean value in your code-behind to true and have that evaluate inside your button. For example:
<button type="button" ng-disabled="issue.IsDisabled" ng-click="AssignRecord(issue.ID,issue.Description,issue.Bid_amt)">Assign</button>
Also, check out the example in their documentation and this jsfiddle: https://jsfiddle.net/simpulton/q8r4e/.
Using Vue, I have displayed table with dynamic data pulled from external JSON.
I want to target the last column in the table body to replace its value with a fixed value for every row.
How would I do this?
Note that my script uses the initial value from the JSON data for that column to determine which class to put on that td.
Here is my code:
var dataURL = 'inc/data.json.php'
Vue.component('demo-grid', {
template: '#grid-template',
replace: true,
props: ['data', 'columns', 'filter-key'],
data: function() {
return {
data: null,
columns: null,
sortKey: '',
filterKey: '',
reversed: {}
}
},
compiled: function() {
// initialize reverse state
var self = this
this.columns.forEach(function(key) {
self.reversed.$add(key, false)
})
},
methods: {
sortBy: function(key) {
this.sortKey = key
this.reversed[key] = !this.reversed[key]
}
}
})
var demo = new Vue({
el: '#app',
data: {
searchQuery: '',
gridColumns: [...],
gridData: []
},
ready: function() {
this.fetchData()
},
methods: {
fetchData: function() {
var xhr = new XMLHttpRequest(),
self = this
xhr.open('GET', programsURL)
xhr.onload = function() {
self.gridData = JSON.parse(xhr.responseText)
}
xhr.send()
}
}
})
<table>
<thead>
<tr>
<th v-repeat="key: columns" v-on="click:sortBy(key)" v-class="active: sortKey == key">
{{key | capitalize}}
<span class="arrow" v-class="reversed[key] ? 'dsc' : 'asc'">
</span>
</th>
</tr>
</thead>
<tbody>
<tr v-repeat="
entry: data
| filterBy filterKey
| orderBy sortKey reversed[sortKey]">
<!-- here is where I wish to target the 5th in this row to change its value -->
<td v-repeat="key: columns" v-class="lvl-1 : entry[key] === '1', lvl-2 : entry[key] === '2', lvl-3 : entry[key] === '3'>
{{entry[key]}}
</td>
</tr>
</tbody>
</table>
Compare the special $index property with the length of the array (or computed property), and then use a template fragment so you can switch out the <td>
<template v-repeat="column in columns">
<td v-show="$index < columns.length-1">All other columns...</td>
<td v-show="$index === columns.length-1">Last Column</td>
</template>
Solved it with:
<div v-if="$index === 4">
...
I am new to knocokout.js so i have a table in which data is bind using ajax call.When user click on edit button row information is fill to a form which is on same page below the table.
after ajax call which update the data into database successfully , i am not able to show the changed value of particular object which is changed into table. If i refresh then its show new value .
Here is my html and js code .
<div id="body">
<h2>
Knockout CRUD Operations with ASP.Net Form App</h2>
<h3>
List of Products</h3>
<table id="products1">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody data-bind="foreach: Products">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: formatCurrency(Price)">
</td>
<td>
<button data-bind="click: $root.edit">
Edit</button>
<button data-bind="click: $root.delete">
Delete</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
</td>
<td>
</td>
<td>
Total :
</td>
<td data-bind="text: formatCurrency($root.Total())">
</td>
<td>
</td>
</tr>
</tfoot>
</table>
<br />
<div style="border-top: solid 2px #282828; width: 430px; height: 10px">
</div>
<div data-bind="if: Product">
<div>
<h2>
Update Product</h2>
</div>
<div>
<label for="productId" data-bind="visible: false">
ID</label>
<label data-bind="text: Product().Id, visible: false">
</label>
</div>
<div>
<label for="name">
Name</label>
<input data-bind="value: Product().Name" type="text" title="Name" />
</div>
<div>
<label for="category">
Category</label>
<input data-bind="value: Product().Category" type="text" title="Category" />
</div>
<div>
<label for="price">
Price</label>
<input data-bind="value: Product().Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.update">
Update</button>
<button data-bind="click: $root.cancel">
Cancel</button>
</div>
</div>
</div>
Code
function formatCurrency(value) {
return "$" + parseFloat(value).toFixed(2);
}
function ProductViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");
var Product = {
Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
// Initialize the view-model
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
// debugger;
$.each(data.d, function (index, prd) {
self.Products.push(prd);
})
//Put the response in ObservableArray
}
});
// Calculate Total of Price After Initialization
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
// Edit product details
self.edit = function (Product) {
self.Product(Product);
}
// Update product details
self.update = function () {
var Product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{Product:" + ko.toJSON(Product) + "}",
success: function (data) {
console.log(data.d);
self.Product(null);
alert("Record Updated Successfully");
},
error: function (data) {
console.log(data);
}
})
}
// Cancel product details
self.cancel = function () {
self.Product(null);
}
}
$(document).ready(function () {
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
});
and my webmethod which called by ajax request is as follow :
// to update product
[WebMethod]
public static testModel.Product Update(testModel.Product Product)
{
testEntities db = new testEntities();
var obj = db.Products.First(o => o.Id == Product.Id);
obj.Name = Product.Name;
obj.Price = Product.Price;
obj.Category = Product.Category;
db.SaveChanges();
return obj;
}
and JSON response of ajax call as follow
{"d":{"__type":"testModel.Product","Id":31,"Name":"12","Category":"12","Price":1350,"EntityState":2,"EntityKey":
{"EntitySetName":"Products","EntityContainerName":"testEntities","EntityKeyValues":
[{"Key":"Id","Value":31}],"IsTemporary":false}}}
Here's what's happening. Here: self.Products.push(prd) prd is just a plain javascript object with plain property values, nothing is observable. You're pushing the raw object onto the Products observableArray, which updates the DOM because Products was changed and KO is watching it. When you click 'edit', you set self.Product to that plain object and the KO updates the DOM with this object and its values because Product was changed and KO is watching it. So now your Product form below displays, you see the information, and it looks like you can edit the properties but KO won't update those property changes because KO isn't watching them. They're not observable. Change:
$.each(data.d, function (index, prd) {
//self.Products.push(prd);
self.Products.push({
Id: ko.observable(prd.Id),
Name: ko.observable(prd.Name),
Price: ko.observable(prd.Price),
Category: ko.observable(prd.Category)
});
});
General helpful tips
<div data-bind="if: Product">
This only evaluates once when you bind the viewModel to the DOM with ko.applyBindings. Since self.Product has an initial value of null KO removes this altogether.*Note: I was thinking of #if for some reason.
This works like the visible binding except when the value is false, the element and its children are removed from the DOM. So there is more DOM manipulation going on than necessary. You probably just want to hide this <div>
I would recommend changing this to:
<div data-bind="visible: Product">
Instead of this:
<input type="text" data-bind="text: Product().Name" />
<input type="text" data-bind="text: Product().Category" />
<input type="text" data-bind="text: Product().Price" />
Try this instead:
<div data-bind="with: Product">
<input type="text" data-bind="text: Name" />
<input type="text" data-bind="text: Category" />
<input type="text" data-bind="text: Price" />
</div>
Consider renaming self.Product to self.SelectedProduct to make it more clear what it is for.
I'm not sure what this is doing in the ViewModel:
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");
var Product = {
Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
You don't use them in the DOM. You were kind of on the right path with this though. Instead, before the ProductViewModel, create this:
function ProductModel(data) {
var self = this;
data = data || {};
self.Id = ko.observable(data.Id);
self.Name = ko.observable(data.Name);
self.Price = ko.observable(data.Price);
self.Category = ko.observable(data.Category);
}
Now instead of:
$.each(data.d, function (index, prd) {
self.Products.push({
Id: ko.observable(prd.Id),
Name: ko.observable(prd.Name),
Price: ko.observable(prd.Price),
Category: ko.observable(prd.Category)
});
});
We can just do this:
$.each(data.d, function (index, prd) {
self.Products.push(new ProductModel(prd));
});
Hopefully that will get you headed in the right direction.
There is something to change:
Replace
$.each(data.d, function (index, prd) {
self.Products.push(prd);
})
With:
$.each(data.d, function (index, prd) {
self.Products.push({
Id: ko.observable(prd.Id),
Name: ko.observable(prd.Name),
Price: ko.observable(prd.Price),
Category: ko.observable(prd.Category)
});
})
Use ko.observable to make your properties notify the view of its changes so that the view can update accordingly. This should work but not perfect because this is 2 way binding, so whenever you update the values in your div, the view model object is updated immediately and even if your ajax fails to update the data in backend, making the data out of synch between client side and server side.
For better solution. You need to have a look at protectedObservable
$.each(data.d, function (index, prd) {
self.Products.push({
Id: ko.protectedObservable(prd.Id),
Name: ko.protectedObservable(prd.Name),
Price: ko.protectedObservable(prd.Price),
Category: ko.protectedObservable(prd.Category)
});
})
Inside your self.update ajax success function, trigger a change:
success: function (data) {
var product =self.Product();
product.Id.commit();
product.Name.commit();
product.Price.commit();
product.Category.commit();
self.Product(null);
alert("Record Updated Successfully");
}
And revert if there is error:
error: function (data) {
product.Id.reset();
product.Name.reset();
product.Price.reset();
product.Category.reset();
}
Update:
Remember to change all the places with Product.Property to Product.Property() to get its property value . For example: arr[i].Price should be changed to arr[i].Price()
Add self.Products.push(data.d); to the update() functions success handler.
success: function (data) {
console.log(data.d);
self.Product(null);
self.Products.push(data.d);
alert("Record Updated Successfully");
},
You need to update the array so that it reflects in bound html.