Dynamic data is not updated in a ngTable - angularjs

I'm using the ngTable directive and the problem is that the data doesn't refresh in the table.
When loading the page, the gemId is undefined and no data shows which is ok.
Then you select a value from a dropdown and when pressing a button the loadItems function is called. Data is retrieved from the server but does not show in the table.
When I filter a column, the data is shown (= 2nd request ).
$scope.tblProject = new ngTableParams(tableParameters, {
counts: [], // hide page counts control
total: $scope.items.length, // value less than count hide pagination
//defaultSort: ['asc','desc'];
getData: function ($defer, params) {
//opgelet: request is geldig ondanks de onbestaand igeID;
var gemId = modelFactory.getGemeente().id;
var igeId = 22222;
if(!angular.isUndefined(gemId)){
Project.query({gemId: gemId, igeId: igeId}, function (projecten) {
var orderedData = params.sorting() ? $filter('orderBy')(projecten, params.orderBy()) : projecten;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
});
}
},
$scope: { $data: {} } //see example 14
});
$scope.$on('loadItems',function() {
$scope.tblProject.reload();
});
Tried all the possible work-arounds for refreshing the table so far, but have had no luck.
edit: I think it is a scope problem when executing the 'loadItems'

The problem was that I was sending an event from the parentController to the childController using $emit instead of $broadcast which executes 'loadItems'

Related

Two ngTables that use same data, but different filter

What I'm trying to do is shown in this CodePen. In my real app, I have tabs, one for each table and this all works fine, but it seems like there's got to be a way to use just one table in the controller and call it with different filters from the view.
Something similar to this, but with a custom filter:
$scope.roleTable = new ngTableParams({
page: 1,
count: 10,
sorting: {
username: 'desc'
}
}, {
counts: [],
getData: function ($defer, params) {
var data = users;
var orderedData = params.sorting() ?
$filter('customFilter')(data, params.filter()) :
data;
params.total(orderedData.length);
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(),
params.page() * params.count()));
}
});
Problem is, I can't figure out how to do it or if it's even possible? I've search stackoverflow, tried passing in params directly from the view to the controller, as well as many other attempts and I can't get it to work.
Is what I want to do even possible?
Maybe something like this: http://codepen.io/anon/pen/eNoMxy?editors=101 ?
$scope.filters = { role: "admin" };
var options = {
page: 1,
count: 10,
filter: $scope.filters,
sorting: {
username: 'desc'
}
};

ngTableParams not working and got an error that length of undefined

I am using angularjs ngTable with filter. When i run the page no table has displayed instead of showing table it showed me an error that says "length of undefined" .
My code snippet is:
var data=$scope.users;
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10, // count per page
sorting: {
name: 'asc' // initial sorting
}
}, {
total: data.length, // length of data
getData: function($defer, params) {
// use build-in angular filter
var orderedData = params.sorting() ?
$filter('orderBy')(data, params.orderBy()) :
data;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
Here '$scope.users' is my array of json objects.
I got an error in line: {total:data.length},
Here is the keyword that show me a response like this "length of undefined".
Any help would be grateful.

displaying params on url disable pagination on ngTable

I want to show table parameters (page, count, filter, etc.) in the url. so I use the following code in my controller :
$scope.tableParams = new ngTableParams(
angular.extend({
page : 1,
count: 10
},
$location.search()), {
getData: function ($defer, params) {
$location.search(params.url()); // put params in url
var query = getQuery();
query.limit = params.count();
query.offset = (params.page() - 1) * params.count();
getTotalCount().success(function () {
Content.prototype.find(query)
.success(function (response) {
$scope.tableParams.total($scope.totalCount);
var data = $filter('populateObjects')(response.data, query.fields);
$defer.resolve(data);
});
});
}
});
I do pagination and filtering on server side.
without applying filters on the table everything goes ok and the pagination works correctly. but every time I apply a filter on the table url change twice. the first time it is ok. something like this :
http://faraketabadmin/src/#/content/list?page=7&count=10&filter%5Bname%5D=g&filter%5Btype_id%5D=4
but after a moment it will again reset to page 1 like this :
http://faraketabadmin/src/#/content/list?page=1&count=10&filter%5Bname%5D=g&filter%5Btype_id%5D=4

AngularJS ngTable not updated

I am using Angular routing in my application as well as ngTable. One of my pages contains a ngTable, and a search form, where data is coming from database using GET method (MongoDB) every time I search, so every time I search the ngTable (table) should be updated, and my problem is that the Table is updated only one time, after loading the page for the first time.
The contoller used for the partial page :
app.controller('SearchController',function($scope,ngTableParams,$http,$filter, $sce){
$scope.searching=function(){
var str = $scope.search.tags;
var TagsArry = str.split(",");
$http.get('/api/GetDoc',{params:{title:$scope.search.title,tags:$scope.search.tags}})
.success(function(data)
{
if(data.notExist!=-1){
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 10 // count per page
}, {
total: data.length, // length of data
getData: function($defer, params) {
$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
});
}
})
.error(function(err){
});
}
});
I was having the same issue. You need to reload $scope.tableParams every time a new search occurs, so every time the search button is clicked. A simple way to do this is to wrap $scope.tableParams.reload() in a function, and then call that function when your search button is clicked.
controller code:
$scope.doSearch = function () {
$scope.tableParams.reload();
}
html code:
<button ng-click="doSearch()">Search</button>
I was also having the similar issue. It is a problem with the ngTable directive. It updates only when data.length changes. I had finally solved this issue, simply add this line before your $http request:
$scope['tableParams'] = {reload:function(){},settings:function(){return {}}};
$http.get('/api/GetDoc',{params:{title:$scope.search.title,tags:$scope.search.tags}})
.success(function(data){
/***** Your Code *********/
});
What it does is, it resets the ng-table settings then it initilize like it does for the first time.

WebSQL data into AngularJs DropDown

I have very simple question about getting data from WebSql
I have DropDown i.e
<select id="selectCatagoryFood" data-role="listview" data-native-menu="true"
ng-init="foodCatagory = foodCatagories.cast[0]"
ng-options="foodCatagory as foodCatagory.text for foodCatagory in foodCatagories.cast"
ng-model="foodCatagory"
ng-change="changeFoodCatagory()">
</select>
now i want to add data init from webSQL. I already get Data from webSql but i am confuse that how to add that data into DropDown
An example or hints maybe very helpful for me.
Update 1 :: Add Controller Code
myApp.controller('foodSelection',function($scope,foodCatagories){
$scope.foodCatagories = foodCatagories;
$scope.changeFoodCatagory = function(){
alert($scope.foodCatagory.value);
}
});
Update 2 webSQL and JayData
_context.onReady({
success: showData,
error: function (error){
console.log(error);
}
});
function showData(){
var option = '';
_context.FoodGroup.forEach(function(FG)
{
option += '<option value="'+FG.FoodGroupID+'">'+FG.Description+'</option>';
}).then(function(){
console.log(option);
});
}
Update 3
var myApp = angular.module('myApp',[]);
myApp.factory('foodCatagories',function(){
var foodCatagories = {};
foodCatagories.cast = [
{
value: "000",
text: "Select Any"
}
];
return foodCatagories;
});
Update 4
One thing that i didn't mention is that I am using JayData for getting data from webSQL to my App
I will try to explain how it works:
EDIT: Live demo
html
Here is your stripped down select.
<select ng-options="item as item.text for item in foodCategories"
ng-model="foodCategory"
ng-required="true"
ng-change="changeFoodCategory()">
</select>
The directive ng-options will fill automatically the option elements in your select. It will take the foodCategories variable from the $scope of your controller and foreach item in the collection, it will use the text property as the label shown (<option>{{item.text}}</option>') and it will select the whole objectitemas the value of the selectedoption. You could also refer to a property as the value like ({{item.text}}). Then yourng-modelwould be set to theid` value of the selected option.
The directive ng-model corresponds to the variable in the $scope of your controller that will hold the value of the selected option.
The directive ng-required allows you to check if a value has been selected. If you are using a form, you can check if the field is valid formName.ngModelName.$valid. See the docs for more details on form validation.
The directive ng-change allows you to execute a function whenever the selected option changes. You may want to pass the ng-model variable to this function as a parameter or call the variable through the $scope inside the controller.
If no default value is set, angular will add an empty option which will be removed when an option is selected.
You did use the ng-init directive to select the first option, but know that you could set the ng-model variable in your controller to the default value you would like or none.
js
Here I tried to simulate your database service by returning a promise in the case that you are doing an async request. I used the $q service to create a promise and $timeout to fake a call to the database.
myApp.factory('DbFoodCategories', function($q, $timeout) {
var foodCategories = [
{ id: 1, text: "Veggies", value: 100 },
{ id: 2, text: "Fruits", value: 50 },
{ id: 3, text: "Pasta", value: 200 },
{ id: 4, text: "Cereals", value: 250 },
{ id: 5, text: "Milk", value: 150 }
];
return {
get: function() {
var deferred = $q.defer();
// Your call to the database in place of the $timeout
$timeout(function() {
var chance = Math.random() > 0.25;
if (chance) {
// if the call is successfull, return data to controller
deferred.resolve(foodCategories);
}
else {
// if the call failed, return an error message
deferred.reject("Error");
}
}, 500);
/* // your code
_context.onReady({
success: function() {
deferred.resolve(_contect.FoodGroup);
},
error: function (error){
deferred.reject("Error");
}
});
*/
// return a promise that we will send a result soon back to the controller, but not now
return deferred.promise;
},
insert: function(item) {
/* ... */
},
update: function(item) {
/* ... */
},
remove: function(item) {
/* ... */
}
};
});
In your controller you set the variables that will be used in your view. So you can call your DbFoodCategories service to load the data into $scope.foodCategories, and set a default value in $scope.foodCategory that will be used to set the selected option.
myApp.controller('FoodSelection',function($scope, DbFoodCategories){
DbFoodCategories.get().then(
// the callback if the request was successfull
function (response) {
$scope.foodCategories = response; //response is the data we sent from the service
},
// the callback if an error occured
function (response) {
// response is the error message we set in the service
// do something like display the message
}
);
// $scope.foodCategory = defaultValue;
$scope.changeFoodCategory = function() {
alert($scope.foodCatagory.value);
}
});
I hope that this helped you understand more in detail what is happening!
See this example and how use $apply to update the data in scope.
in the new version we released a new module to support AngularJS. We've started to document how to use it, you can find the first blogpost here
With this you should be able to create your dropdown easily, no need to create the options manually. Something like this should do the trick:
myApp.controller('foodSelection',function($scope, $data) {
$scope.foodCatagories = [];
...
_context.onReady()
.then(function() {
$scope.foodCatagories = _context.FoodGroup.toLiveArray();
});
});
provided that FoodGroup has the right fields, of course

Resources