ng-grid column size problems. And ng-if issue - angularjs

I am having problems with my grid column widths in ng-grid. My issue is that I don't know ahead of time what the columns will be (they are retrieved from a service call at the same time as the values. My Json object has two properties in it. An array of strings for column names and then a 2d array for values. currently the columns do not size to fit the column headers. I understand the columns will resize to fit the row data but what if no results are returned. then you have a mess. I tried making it so I did not have to set grid options until I had my data but then get an undefined error. I saw another post where the solution for that was to use ng-if in the div tag so the grid does not load until you want it to. that did not work either as the grid still tried to load before the if statement was satisfied. Below is my code. any thoughts? also,my ng-if was like this: ng-if="contentAvailable". Also adding a screen shot. My expectations would be for a horizontal scrollbar to show up.
app.controller('mainController',function($scope,dataFactory){
$scope.contentAvailable = false;
$scope.gridOptions = {
columnDefs: 'columns',
showGroupPanel: true
};
$scope.url = 'http://example.com';
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.indexOf(str) == 0;
};
}
$scope.Fetch = function () {
dataFactory.Fetch($scope.url,$scope.config).success(function (blah) {
var result = $scope.transformJsonDataSet(blah);
})
.error(function (error) {
$scope.result = error;
});
};
$scope.transformJsonDataSet = function (ds) {
var tmp = angular.fromJson(ds);
var fieldNames = tmp.FieldNames;
var fieldValues = tmp.FieldValues;
var columns = [];
for (var i = 1; i < fieldNames.length; i++) {
if (fieldNames[i].startsWith('DECODE_') == false) {
columns.push({ field: fieldNames[i], displayName: fieldNames[i], cellClass: 'headerStyle'});
}
}
$scope.columns = columns;
$scope.contentAvailable = true;
return ds;
};
});
app.factory('dataFactory', ['$http', function ($http) {
var dataFactory = {};
dataFactory.Fetch = function (url,config) {
return $http.get(url,config);
};
return dataFactory;
}]);

There's no $scope.columns declared in your controller?
Try defining a $scope.columns variable and assign it an empty variable:
app.controller('mainController',function($scope,dataFactory){
$scope.contentAvailable = false;
$scope.columns = [];
$scope.gridOptions = {
columnDefs: 'columns',
showGroupPanel: true
};
/* */

Related

How to merge REST call results in Angular app more efficiently

I have an Angular SPA running on a SharePoint 2013 page. In the code, I'm using $q to pull data from 10 different SharePoint lists using REST and then merging them into one JSON object for use in a grid. The code runs and outputs the intended merged data but it's leaky and crashes the browser after a while.
Here's the code in the service:
factory.getGridInfo = function() {
var deferred = $q.defer();
var list_1a = CRUDFactory.getListItems("ListA", "column1,column2,column3");
var list_1b = CRUDFactory.getListItems("ListB", "column1,column2,column3");
var list_2a = CRUDFactory.getListItems("ListC", "column4");
var list_2b = CRUDFactory.getListItems("ListD", "column4");
var list_3a = CRUDFactory.getListItems("ListE", "column5");
var list_3b = CRUDFactory.getListItems("ListF", "column5");
var list_4a = CRUDFactory.getListItems("ListG", "column6");
var list_4b = CRUDFactory.getListItems("ListH", "column6");
var list_5a = CRUDFactory.getListItems("ListI", "column7");
var list_5b = CRUDFactory.getListItems("ListJ", "column7");
$q.all([list_1a, list_1b, list_2a, list_2b, list_3a, list_3b, list_4a, list_4b, list_5a, list_5b])
.then(function(results){
var results_1a = results[0].data.d.results;
var results_1b = results[1].data.d.results;
var results_2a = results[2].data.d.results;
var results_2b = results[3].data.d.results;
var results_3a = results[4].data.d.results;
var results_3b = results[5].data.d.results;
var results_4a = results[6].data.d.results;
var results_4b = results[7].data.d.results;
var results_5a = results[8].data.d.results;
var results_5b = results[9].data.d.results;
var combined_1 = results_1a.concat(results_1b);
var combined_2 = results_2a.concat(results_2b);
var combined_3 = results_3a.concat(results_3b);
var combined_4 = results_4a.concat(results_4b);
var combined_5 = results_5a.concat(results_5b);
for(var i = 0; i < combined_1.length; i++){
var currObj = combined_1[i];
currObj["column4"] = combined_2[i].column4;
currObj["column5"] = combined_3[i].column5;
currObj["column6"] = combined_4[i].column6;
currObj["column7"] = combined_5[i].column7;
factory.newObjectArray[i] = currObj;
}
deferred.resolve(factory.newObjectArray);
},
function (error) {
deferred.reject(error);
});
return deferred.promise;
};
Here's the REST call in CRUDFactory:
factory.getListItems = function (listName, columns){
var webUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('"+listName+"')/items?$select="+columns+"&$top=5000";
var options = {
headers: { "Accept": "application/json; odata=verbose" },
method: 'GET',
url: webUrl
};
return $http(options);
};
And then here's the controller bit:
$scope.refreshGridData = function(){
$scope.hideLoadingGif = false;
$scope.GridData = "";
GlobalFactory.getGridInfo()
.then(function(){
$scope.GridData = GlobalFactory.newObjectArray;
$scope.hideLoadingGif = true;
});
};
UPDATE 1: Per request, Here's the HTML (just a simple div that we're using angular-ui-grid on)
<div ui-grid="GridOptions" class="grid" ui-grid-selection ui-grid-exporter ui-grid-save-state></div>
This code starts by declaring some get calls and then uses $q.all to iterate over the calls and get the data. It then stores the results and merges them down to 5 total arrays. Then, because my list structure is proper and static, I'm able to iterate over one of the merged arrays and pull data from the other arrays into one master array that I'm assigning to factory.newObjectArray, which I'm declaring as a global in my service and using as my grid data source.
The code runs and doesn't kick any errors up but the issue is with (I believe) the "getGridInfo" function. If I don't comment out any of the REST calls, the browser uses 45 MB of data that doesn't get picked up by GC which is then compounded for each click until the session is ended or crashes. If I comment out all the calls but one, my page only uses 18.4 MB of memory, which is high but I can live with it.
So what's the deal? Do I need to destroy something somewhere? If so, what and how? Or does this relate back to the REST function I'm using?
UPDATE 2: The return result that the grid is using (the factory.newObjectArray) contains a total of 5,450 items and each item has about 80 properties after the merge. The code above is simplified and shows the pulling of a couple columns per list, but in actuality, I'm pulling 5-10 columns per list.
At the end of the day you are dealing with a lot of data, so memory problems are potentially always going to be an issue and you should probably consider whether you need to have all the data in memory.
The main goal you should probably be trying to achieve is limiting duplication of arrays, and trying to keep the memory footprint as low as possible, and freeing memory as fast as possible when you're done processing.
Please consider the following. You mention the actual number of columns being returned are more than your example so I have taken that into account.
factory.getGridInfo = function () {
var deferred = $q.defer(),
// list definitions
lists = [
{ name: 'ListA', columns: ['column1', 'column2', 'column3'] },
{ name: 'ListB', columns: ['column1', 'column2', 'column3'], combineWith: 'ListA' },
{ name: 'ListC', columns: ['column4'] },
{ name: 'ListD', columns: ['column4'], combineWith: 'ListC' },
{ name: 'ListE', columns: ['column5'] },
{ name: 'ListF', columns: ['column5'], combineWith: 'ListE' },
{ name: 'ListG', columns: ['column6'] },
{ name: 'ListH', columns: ['column6'], combineWith: 'ListG' },
{ name: 'ListI', columns: ['column7'] },
{ name: 'ListJ', columns: ['column7'], combineWith: 'ListI' },
],
// Combines two arrays without creating a new array, mindful of lenth limitations
combineArrays = function (a, b) {
var len = b.length;
for (var i = 0; i < len; i = i + 5000) {
a.unshift.apply(a, b.slice(i, i + 5000));
}
};
$q.all(lists.map(function (list) { return CRUDFactory.getListItems(list.name, list.columns.join()); }))
.then(function (results) {
var listResultMap = {}, var baseList = 'ListA';
// map our results to our list names
for(var i = 0; i < results.length; i++) {
listResultMap[lists[i].name] = results[i].data.d.results;
}
// loop around our lists
for(var i = 0; i < lists.length; i++) {
var listName = lists[i].name, combineWith = lists[i].combineWith;
if(combineWith) {
combineArrays(listResultMap[combineWith], listResultMap[listName]);
delete listResultMap[listName];
}
}
// build result
factory.newObjectArray = listResultMap[baseList].map(function(item) {
for(var i = 0; i < lists.length; i++) {
if(list.name !== baseList) {
for(var c = 0; c < lists[i].columns.length; c++) {
var columnName = lists[i].columns[c];
item[columnName] = listResultMap[list.name][columnName];
}
}
}
return item;
});
// clean up our remaining results
for (var i = 0; i < results.length; i++) {
delete results[i].data.d.results;
delete results[i];
}
deferred.resolve(factory.newObjectArray);
},
function (error) {
deferred.reject(error);
});
return deferred.promise;
};
I would suggest to add some sort of paging option... It's perhaps not a great idea to add all results to one big list.
Next i would suggest against ng-repeat or add a "track by" to the repeat function.
Check out: http://www.alexkras.com/11-tips-to-improve-angularjs-performance/
Fiddler your queries, the issue is probably rendering all the elements in the dom... Which could be kinda slow ( investigate)

angular ui-grid : how to use a variable parameter in the field property

In my ui-grid, I need to bring the value given by the function of my personModel:
{field:'getValue("weight")',displayName:'Weight'},
But, I need to pass an other variable parameter to this function regarding to a date like this :
$scope.myDate=new Date();
{field:'getValue("weight",myDate)',displayName:'Weight'},
How can I achieve it ?
I would dynamically add this field to my data array after loading the data.
{field:'weightByDate', displayName:'Weight'},
and then
$scope.myDate=new Date();
$q.all([
myDataLoaderFunction.$promise
])
.then(function (data) {
for (var i = 0; i < data[0].length; i++) {
data[0][i]['weightByDate'] = $scope.getValue('weight', myDate);
}
$scope.gridOptions.data = data[0];
}, function () {
$scope.gridOptions.data = [];
});
Perhaps that would work for you? (Note I have not run this code, there might be a syntax error in there somewhere.)

Create an AngularJS factory / object to hold an array

How can I update this code to hold an array of values? I want to hold FIELDNAME and the VALUE.
I want to set / add to the list by doing the following - add a value to the array/list.
userFilters.setData(' lastname', 'smith');
userFilters.setData(' firstname', 'bob');
userFilters.setData(' Mi', 'D');
And have the object hold an Array of
'lastname','smith'
'firstname','bob'
'mi','D'
App.factory('userFilters', [function () {
var data = {};
var getData = function (field) {
return data[field];
};
var setData = function (field, value) {
data[field] = value;
};
return {
getData: getData,
setData: setData
}
}]);
You could recreate this fairly simply without any need for the methods you are creating.
Javascript Objects are designed to do exactly what you are looking for here.
App.factory('userFilters', function() {
return {};
});
Rather than using a getter and setter, you could instead get and set values with square bracket accessors.
// setting properties
userFilters['lastname'] = 'smith';
userFilters['firstname'] = 'bob';
userFilters['Mi'] = 'D';
// getting properties
userFilters['lastname']; // 'smith'
userFilters['firstname']; // 'smith'
If you want to be able to have full control of what happens at get/set time, you could look at intercepting these calls with internal getters and setters, providing you know the property names before hand.
Finally, you could also wrap your own get and set functions around the object in order to hide it. However, this would make more sense as a Service.
App.service('userFilters', function() {
var store = {};
this.get = function(key) {
return store[key];
};
this.set = function(key, value) {
store[key] = value;
};
});
If it's important that your factory/service exposes an array then I would recommend sticking to using an object to store keys and values, but adding an array export method.
App.service('userFilters', function() {
var store = {};
this.toArray = function() {
var records = [];
return Object.keys(store).map(function(key) {
records.push([key, store[key]]);
});
};
this.get = function(key) {
return store[key];
};
this.set = function(key, value) {
store[key] = value;
};
});
If you want to loop through the properties, you can use a for-in loop.
for(var key in userFilters) {
var value = userFilters[key];
console.log(key, value);
}
You can also check whether there any keys at all, using the Object.keys method.
Object.keys(userFilters); // ['lastname', 'firstname', 'Mi']
This will return an array of all the keys in the object. If it has length 0, then you know it's empty.
In order to use an array for storage you will need to update both getData and setData methods and define data as an array []:
App.factory('userFilters', [function () {
var data = [];
var getData = function (field) {
for(var i=0; i<data.length; i+=2) {
if(data[i] == field) {
return data[i+1];
}
}
return null;
};
var setData = function (field, value) {
data = data.concat([field, value]);
};
return {
getData: getData,
setData: setData
}
}]);

AngularJS, Add Rows

Morning,
We are trying to implement this add row Plunkr, it seems to work however our input data seems to repeat. Does anyone know of a solution to add a unique id to preview duplicated fields ?
Here is our current Plunkr and LIVE example.
$scope.addRow = function(){
var row = {};
$scope.productdata.push(row);
};
$scope.removeRow = function(index){
$scope.productdata.splice(index, 1);
};
$scope.formData you have is not an array, but just one object. All your rows are bound to that object and hence all of them reference the same data.
The reason you get a new row added is because your ng-repeat is bound to $scope.productData and you add extra record in it. You should bind your form elements to the properties in the row object that you create
a simple example is :
In your template
<div ng-repeat="product in products">
<input type="text" ng-model="product.title">
</div>
In your controller
$scope.addProduct = function(){
var product = {};
$scope.productData.add(product);
}
You'd then always only work with the productData array and bind your model to them.
Even in your backend calls, you'd use productData instead of your formData.
Hope this helps.
U can use a filter : This will return Unique rows only
app.filter('unique', function () {
return function (items, filterOn) {
if (filterOn === false) {
return items;
}
if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
var hashCheck = {}, newItems = [];
var extractValueToCompare = function (item) {
if (angular.isObject(item) && angular.isString(filterOn)) {
return item[filterOn];
} else {
return item;
}
};
angular.forEach(items, function (item) {
var valueToCheck, isDuplicate = false;
for (var i = 0; i < newItems.length; i++) {
if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
newItems.push(item);
}
});
items = newItems;
}
return items;
};
});
I think the reason why this is happening is that the addRow() function is just pushing an empty son object into the $scope.productdata array, whereas all input fields are bound to $scope.formData[product.WarrantyTestDescription]. I think you mean to bind the input fields to the properties of the product object.

Angular JS Promise - Binding inside a forEach loop

I am using angular.forEach to iterate over an array and for each value in the array, I am using a GET/ to retrieve it's name (array contains key), then push that name into another array. This new array is being used in a dropdown box (ngOptions).
The issue I am having is that the drop down is being created before the GET/ responses have arrived, so it just displays blank options, then when they arrive it displays all options in each drop down.
I have the following code:
angular.forEach($scope.pots, function(value, key) {
$scope.selections = [];
angular.forEach(value, function(val, ky) {
if (ky === "selections") {
angular.forEach(val, function(v, k) {
$http.get('/selections/' + v).then(function(response) {
var response = response.data;
$scope.selection = response[0];
$scope.selectionName = $scope.selection.name;
$scope.selections.push({name : $scope.selectionName});
value["selectionNames"] = $scope.selections;
})
})
}
})
value["selectionNames"] = $scope.selections;
console.log(value);
So I am iterating over a list of pots which contains a list of selections, using the GET/ to get a list of names based on the list of selections and finally pushing that into the pot's scope. I am resetting the selection after each pot.
What's causing the issue is that reponses all come at once, and they bypass the $scope.selections = []; code, so it just pushes into each pot the complete array from all three pots.
Any tips/advice please? Thank you.
So looks like I've fixed it... Can someone confirm that this is good practice please? I'm basically recreating $scope.selections each time I iterate based on the selectionNames value in the pot (value).
angular.forEach($scope.pots, function(value, key) {
$scope.selections = [];
angular.forEach(value, function(val, ky) {
if (ky === "selections") {
angular.forEach(val, function(v, k) {
$http.get('/selections/' + v).then(function(response) {
$scope.selections = [];
var response = response.data;
$scope.selection = response[0];
$scope.selectionName = $scope.selection.name;
var currentSelections = value.selectionNames;
angular.forEach(currentSelections, function(csV, csK) {
$scope.selections.push(csv);
})
$scope.selections.push({name : $scope.selectionName});
value["selectionNames"] = $scope.selections;
})
})
}
})
value["selectionNames"] = $scope.selections;
console.log(value);

Resources