Hope you are doing good..
I'm trying to fetch single record from datasource by Id in UI via Angular-js.
Using Web-API for retrieving values from DB.
To make it simple : HTML-->Angular-->WebAPI-->DB
When i'm trying it says Id passed is Null..Don't know how to rectify.
hope i've missed to fill hole in somewhere....below snippets fr ref.
(Also can u verify/correct me the way i've coded in html is right way to display values fetched by Id)
HTML :
<div ng-controller="SingleController">
<input type="text" ng-model="_Id" />
<input type="button" value="search" ng-click="search()" />
<table>
<tr>
<td>MovieId</td>
<td>{{MovID}}</td>
</tr>
<tr>
<td>Title</td>
<td>{{Movtitle}}</td>
</tr>
<tr>
<td>Genre</td>
<td>{{Movgnre}}</td>
</tr>
<tr>
<td>Classification</td>
<td>{{Movcls}}</td>
</tr>
<tr>
<td>ReleaseDate</td>
<td>{{Movdate}}</td>
</tr>
<tr>
<td>Rating</td>
<td>{{Movrate}}</td>
</tr>
<tr>
<td>Cast</td>
<td>{{Cast}}</td>
</tr>
</table>
</div>
Controller.JS
app.controller('SingleController', function ($scope, MyService) {
var Id = $scope._Id;
$scope.search = function (Id) {
var promiseGetSingle = MyService.getbyId(Id);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.MovID = res._movieId;
$scope.Movtitle = res._title;
$scope.Movgnre = res._genre;
$scope.Movcls = res._classification;
$scope.Movdate = res._releaseDate;
$scope.Movrate = res._rating;
$scope.Cast = res._cast;
// $scope.IsNewRecord = 0;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
}
});
service.js
this.getbyId = function (Id) {
return $http.get("/api/values/" + Id);
};
Please ignore this lengthy snippets.
Could you please help me on this.
Your search function is expecting you to pass a value when it is invoked on ng-click:
<input type="button" value="search" ng-click="search(_Id)" />
Related
i recently discover Knockout and i'm struggling for getting properties of an object in a foreach:
Here is my code :
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Created By</th>
</tr>
</thead>
<tbody data-bind="foreach: assets">
<tr class="assets" data-bind="click: $parent.detailPage">
<td>
<span data-bind="text: FileName"></span>
</td>
<td>
<span data-bind="text: CreatedBy"></span>
</td>
</tr>
</tbody>
and my script :
<script>
function ViewModel(assets) {
var self = this;
self.assets = assets;
self.detailPage = function (asset) {
location.href = '#Url.Action("Details", "Assets")/' + asset.Id;
};
};
var jsonModel = new ViewModel(#Html.Raw(Json.Encode(Model)));
var viewModel = ko.mapping.fromJS(jsonModel);
ko.applyBindings(viewModel);
In my assets, i have an id and i would like to open my view using the id of the object i click on.
But when i execute that, the url become : http://localhost:62677/Assets/Details/[object Object]
Any idee for doing this properly ?
Thanks !
Assuming that asset.Id is a knockout observable, try this
self.detailPage = function (asset) {
location.href = '#Url.Action("Details", "Assets")/' + asset.Id();
};
Looks like asset.Id is an object.
Try to investigate why it is object and not some number or string.
I have an angular function to call me rest service but it can't get the value from the html file. when i press submit the $scope.productForm is, although i still have value in my html page.
Main.js
$scope.products = [];
$scope.productForm = {
ID:1,
Name:"",
Description:"",
URL:""
};
_refreshProductData();
//Add or Update Product
$scope.submitProduct = function() {
var method = "";
if ($scope.productForm.ID == -1) {
method = "POST";
} else {
method = "PUT";
}
$http({
method: method,
url: '/product',
data: angular.toJson($scope.productForm),
headers: {
'Content-Type': 'application/json'
}
}).then(_success, _error);
}
index.html
<form ng-submit="submitProduct()">
<table border="0">
<tr>
<td>ProductID</td>
<td>{{productForm.ID}}</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="text" ng-model="productForm.Name" /></td>
</tr>
<tr>
<td>Product Description</td>
<td><input type="text" ng-model="productForm.Description" /></td>
</tr>
<tr>
<td>Product URL</td>
<td><input type="text" ng-model="productForm.URL" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" class="blue-button" />
</td>
</tr>
</table>
</form>
data: angular.toJson($scope.productForm) can have value from index.html
Like others have said, you have a number of things you need to address.
main.js doesn't have a function _refreshProductData defined. I'm assuming this is breaking your script and why $scope.submitProduct() isn't executing.
When defining your _refreshProductData function, you need to attach it to the controller's $scope(i.e. $scope._refreshProductData = function(){//refresh data} if you want it to be accessible to the html template. Otherwise, you wouldn't need to attach $scope to it. You would need to update your call to this function based on the approach you take.
$scope._refreshProductData();--> you should call your function this way.
_refreshProductData();-->_refreshProductData is not defined(F12)
I have assumed that the function was created in my previous answer.
1)create your function in main.js
$scope._refreshProductData() = function()
{
write codes here...
}
then call the function in place
2) $scope._refreshProductData();
Suppose you have a html table of the
<form id="myForm">
<table id="myTable">
<tr>
<th>One</th>
<th>Two</th>
<th>Three</th>
</tr>
<tr>
<td>Alpha</td>
<td>Bravo</td>
<td>X</td>
</tr>
<tr>
<td>Charlie</td>
<td>Delta</td>
<td>X</td>
</tr>
<tr>
<td>Echo</td>
<td>Foxtrot</td>
<td>X</td>
</tr>
</table>
</form>
Reset
I have the following javascript
var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;
function remove(rowID)
{
table.deleteRow(rowID);
}
function reset()
{
form.innerHTML = formSave;
}
For some reason, the remove() function works fine, but after using the reset() function, it no longer works. Can anyone tell me why this is?
As var table is a live 'Element object' it's properties are updated each time you delete a row. By the time you deploy the reset() function var table references less Children than the restored HTML. Opening the console will show you have an indexing error on subsequent uses of the function bound to "X".
You can remedy this by re-acquiring the element in the reset function, like so...
var table = document.getElementById('myTable');
var form = document.getElementById('myForm');
var formSave = form.innerHTML;
function remove(rowID) {
table.deleteRow(rowID);
}
function reset() {
form.innerHTML = formSave;
/* re-acquire 'new' (inserted) table */
table = document.getElementById('myTable');
}
Hope that helped :)
I'm trying to implement this boostrap datatable:
https://datatables.net/examples/api/add_row.html
...but I'd like to add data given by the user in a form rather than pre-set data. I'm storing the form data in localStorage.
I know I need to stringify and parse the data. I've added some pseudocode, along with some commentary as to what I think needs to be done, but I'm stuck.
JSfiddle:
http://jsfiddle.net/wad11656/bkoze96c/8/
HTML:
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Entry Date</th>
<th>Feedback</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Entry Date</th>
<th>Feedback</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>2011/04/25</td>
<td>Different color scheme</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>2011/07/25</td>
<td>Change the menu</td>
</tr>
<tr>
<td>Bob Parker</td>
<td>2014/04/23</td>
<td>Get more sleep--you look awful!</td>
</tr>
<tr>
<td>Wendy-Sue</td>
<td>2014/04/27</td>
<td>Call me more often</td>
</tr>
</tbody>
</table>
<!-- Form -->
<form method="post" action="">
<input name="name" id="name" type="text" class="stored" placeholder="Name" autofocus="" required="">
<br>
<textarea name="feedback" id="feedback" class="stored" placeholder="Endorsement" rows="3" required=""></textarea>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="submit_button" onclick="append_feedback();">Submit</button>
</form>
Javscript:
// Ready Table:
$(document).ready(function () {
var t = $('#example').DataTable();
var counter = 1;
});
// Store data in local storage:
$(document).ready(function () {
function init() {
if (localStorage["name"]) {
$('#name').val(localStorage["name"]);
}
if (localStorage["feedback"]) {
$('#feedback').val(localStorage["feedback"]);
}
}
init();
});
$('.stored').keyup(function () {
localStorage[$(this).attr('name')] = $(this).val();
});
$('#localStorageTest').submit(function () {
localStorage.clear();
});
//Rough draft of Functions for adding row from localStorage data:
/*
var jsonarray = [];
var name;
var feedback;
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var today = month + "/" + day + "/" + year;
var message;
document.getElementById("submit_button").addEventListener("click", submit);
function submit() {
var t = $('#example').DataTable();
t.clear();
// Clear out table with .clear() see api doc
// Grab JSON array
// parse JSON array form local storage to jsonArray
jsonarray = JSON.parse(localStorage.getItem("storage"));
// for each (var message in jsonArray)
//look for how to loop through JSON array in js
endorsements.forEach(var (message)
t.row.add([
message[name],
message[date],
message[feedback], ]).draw();
});
}
function localsave() {
localStorage.Name = document.getElementById("name").value;
localStorage.Words = document.getElementById("feedback").value;
// Put name and message into key value pair for JSON
[{"name":"namethatwasinputeed","date":"1/28/2015","feedback":"messagethatwasinputedfromlocalstorage", },
{"name":"namethatwasinputeed","date":"1/28/2015","feedback":"messagethatwasinputedfromlocalstorage", },
{"name":"namethatwasinputeed","date":"1/28/2015","feedback":"messagethatwasinputedfromlocalstorage", }]
//Stringify to turn into JSON string array
localStorage["storage"] = JSON.stringify(message);
}
*/
LocalStorage has it's own API. You could get unintended results if you don't use it
Basically, you need to do something like this.
if(window.localStorage) { // not all browsers have it
var output;
localStorage.setItem('test', 'value');
output = localStorage.getItem('test');
console.log(output); // value
}
You could also checkout a library called Kizzy which does localStorage well
For you're issue, you should try putting everything inside a document.ready along with all your other commented code, or jQuery will not work properly
// Ready Table:
$(document).ready(function () {
var t = $('#example').DataTable();
var counter = 1;
function init() {
if (localStorage["name"]) {
$('#name').val(localStorage["name"]);
}
if (localStorage["feedback"]) {
$('#feedback').val(localStorage["feedback"]);
}
}
init();
$('.stored').keyup(function () {
localStorage[$(this).attr('name')] = $(this).val();
});
$('#localStorageTest').submit(function () {
localStorage.clear();
});
});
I'm trying to generate HTML table from json in AngularJS.
I receive JSON in format like this:
My Service for getting the data looks like this :
customAPI.getUsers = function() {
return $http({
method: 'JSONP',
url: 'http://arka.foi.hr/WebDiP/2013_projekti/WebDiP2013_069/api/admin/users.php'
});
};
and controller for that code looks like this
controller('usersController', function($scope, customAPIservice) {
$scope.filterName = null;
$scope.usersList = [];
/*Search*/
$scope.searchFilter = function(user) {
var keyword = new RegExp($scope.filterName, 'i');
return !$scope.filterName || keyword.test(user.korisnici.korisnik_ime) || keyword.test(user.korisnici.korisnik_prezime);
};
customAPIservice.getUsers().success(function(response) {
$scope.usersList = response.korisnici;
});
});
and my view looks like this :
<input type="text" ng-model="nameFilter" placeholder="Trazi..."/>
<h2 >Korisnici</h2>
<table>
<thead>
<tr>
<th colspan="6">Korisnici sustava</th>
</tr>
<th>Surname</th>
</thead>
<tbody>
<tr ng-repeat="user in usersList| filter: searchFilter">
<td>{{$index + 1}}</td>
<td>{{user.korisnik.korisnik_prezime}}</td>
<td>{{user.korisnik.korisnik_username}}</td>
</tr>
<tr ng-show="usersList == ''">
<td colspan="5">
<img src="img/ajax-loader.gif" />
</td>
</tr>
</tbody>
</table>
I think I messed up somewhere with binding the data with the view but I' still pretty new with angular so I can't find what is wrong. Also I've looked up over internet and couldn't find anything.Please help.
You are not correctly access the properties in your data. Use:
/*Search*/
$scope.searchFilter = function(user) {
var keyword = new RegExp($scope.filterName, 'i');
return !$scope.filterName || keyword.test(user.korisnik.korisnik_ime) || keyword.test(user.korisnik.korisnik_prezime);
};