Data binding to syncfusion grid using custom service not working - angularjs

I have used syncfusion grid and i want to bind data to syncfusion grid from API
but data binding to syncfusion grid is not working
here is HTml code for grid
<div ng-controller="ContactsController as contact">
<div id="Grid" ej-grid e-datasource="contact.Cdata" e-columns="contact.columns" e-toolbarsettings='contact.tools' e-toolbarclick="contact.toolbarHandler"
e-editsettings="contact.edittsetings" e-allowsorting="contact.allowsorting" e-sortsettings="contact.sortsettings" e-actionbegin="contact.actionBegin" e-allowpaging="contact.allowpaging"
e-pagesettings="contact.pagesettings" e-editsettings="contact.editsettings" e-allowreordering="contact.allowReordering" e-allowresizing="contact.allowResizing">
</div>
</div>
Here is Controller method::
function ContactsController(CommonService) {
this.Cdata = [];
var d = CommonService.getCantactList();
d.then(function (response) {
ContactsController.prototype.Cdata = response.data.Items;;
console.log("success");
}, function (error) {
console.log("error");
});
}
and the commonService is
this.getCantactList = function () {
return $http.get("http://localhost:63138/api/Contact/GetContactsbyClientId?clientId=1", { cache: true });
}
And the API method is::
public object GetContactsbyClientId(int clientId)
{
try
{
//return (ContactService.GetListByClientId(clientId));
return new { Items = ContactService.GetListByClientId(clientId) };
}
catch (Exception)
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error occurred, please try again or contact the administrator."),
ReasonPhrase = "Critical Exception"
});
}
}

The problem might be due to the below line.
ContactsController.prototype.Cdata = response.data.Items;;
It should be as follows.
function ContactsController(CommonService) {
this.Cdata = [];
proxy = this;
var d = CommonService.getCantactList();
d.then(function (response) {
proxy.Cdata = response.data.Items;
console.log("success");
}, function (error) {
console.log("error");
});
Now it will work as expected.

Related

Backbone collection on save error

I'm trying to get it so that when my backbone collection is saving if it hits an error I can do something with it. However when the form is saved the Render All Tasks button's click event is always triggered. How can I get it to stop iterating the collection if an error is found? Or otherwise how can I get it to call the fail function?
var EditTaskView = AddTaskView.extend({
template: _.template($("#individualTaskEditView").html()),
events: {
"submit": function (e) {
e.preventDefault();
if (this.model.isValid(true) && this.ScheduleView.isValid() && this.ProviderView.isValid()) {
$.when(this.model.save(), this.FiltersView.saveAll())
.done(function () {
$("#RenderAllTasks").trigger("click");
})
.fail(function (xhr, status, errorMessage) {
var message = JSON.parse(xhr.responseText).Message;
RenderError(message, "#EditTaskDetailsTabError");
});
}
}
}
};
var FieldCollectionAddView = Backbone.View.extend({
tagName: "div",
render: function () {
// iterate the collection
this.collection.each(function (field) {
// render the view and append to the collection
var view = new FieldAddView({ model: field });
var rendered = view.render();
this.$el.append(rendered.el);
}, this);
return this;
},
isValid: function () {
var valid = true;
_.each(this.collection.models, function (model) {
if (!model.isValid(true)) {
valid = false;
}
});
return valid;
},
saveAll: function () {
var errorsFound = false;
_.each(this.collection.models, function (model) {
model.save(null, {
error: function (error) {
//TODO: do soemthing with the error
var message = JSON.parse(el.responseText).Message;
RenderError(message, "#ProviderDetailsTabError");
}
}, { wait: true });
});
return errorsFound;
}
});
var ProviderAddView = Backbone.View.extend({
tagName: "div",
template: _.template($("#providerAddTemplate").html()),
render: function () {
// append the template to the element
this.$el.append(this.template);
//render provider types
this.ProviderTypes = RenderProviderTypes(this.model.attributes.ProviderTypes);
var providerTypesDiv = _.template($("#ProviderTypesTemplate").html());
$("#ProviderTypesDiv", this.$el).html(providerTypesDiv);
$("#ProviderTypesSelectDiv", this.$el).html(this.ProviderTypes.render().el);
$("#ProviderTypes", this.$el).val(this.model.attributes.ProviderType);
// render field collection
var collection = new FieldCollection(this.model.attributes.ProviderFieldList);
var fieldsView = new FieldCollectionAddView({
collection: collection
});
this.FieldsAddView = fieldsView;
// append the fields to the element
$("#fieldsDiv", this.$el).append(fieldsView.render().el);
this.stickit();
return this;
},
events: {
"submit #NewProviderForm": function (e) {
e.preventDefault();
if (this.FieldsAddView.isValid()) {
var fieldsView = this.FieldsAddView;
this.model.save(null, {}, { wait: true })
.success(function (result) {
var filters = new FilterCollection();
$.when(fieldsView.saveAll(),
filters.fetch({
data: $.param({
taskId: result.attributes.TaskId
})
}))
.done(function() {
if (!$("#FiltersForm").html()) {
var view = new FilterCollectionView({ collection: filters });
assign(view, "#FilterDetails");
$("#FiltersForm").append(buttonsTemplate);
$("#FilterDetailsTab").parent("li").removeClass("disabled");
$("#FilterDetailsTab").attr("data-toggle", "tab");
}
$("#FilterDetailsTab").tab("show");
});
})
.error(function (xhr, el, other) {
var message = JSON.parse(el.responseText).Message;
RenderError(message, "#ProviderDetailsTabError");
});
}
}
},
isValid: function () {
return this.model.isValid(true) && this.FieldsAddView.isValid();
},
save: function () {
this.model.save();
this.FieldsAddView.saveAll();
}
});
Ok, so I found how this has to be done. In short the code had to be changed so that it was syncing the entire collection at once using Backbone.sync instead of iterating over it and saving each model individually. Also when you're ready to save the collection you use the $.when function so it completes the whole sync before deciding what to do. Below is the relevant code showing the changes that were made.
var FieldCollection = Backbone.Collection.extend({
url: "/api/Field",
model: FieldModel,
syncAll: function () {
return Backbone.sync("create", this)
.error(function (xhr, el, other) {
var message = JSON.parse(xhr.responseText).Message;
var tab = "";
var activeTab = $("#Tabs li.active a").attr("id");
if (activeTab === "TaskListTab") {
tab = "#EditTaskDetailsTabError";
}
else if (activeTab === "NewTaskTab") {
tab = "#ProviderDetailsTabError";
}
RenderError(message, tab);
});
}
});
var FieldCollectionAddView = Backbone.View.extend({
saveAll: function () {
return this.collection.syncAll();
}
});
var ProviderAddView = Backbone.View.extend({
events: {
"submit #NewProviderForm": function (e) {
e.preventDefault();
if (this.FieldsAddView.isValid()) {
var fieldsView = this.FieldsAddView;
$.when(fieldsView.saveAll())
.done(function() {
// success
});
}
}
}
});

No popup window with AngularJS and typeahead

I have a problem with the typeahead directive. I try to get datas from my datas from my service via $http.get.
In the console output I can see that my datas are coming from the service but I don't get the popup window of the results.
Here is my code:
Html Template:
<input type="text" class="form-control" placeholder="Kundensuche" ng-model="selectedCompany" typeahead="c for c in companies($viewValue)" typeahead-no-results="noResults" typeahead-min-length="3">
Service:
var _search = function (route, id) {
return $http.get(serviceBase + 'api/' + route + '/search/' + id);
};
serviceHelperFactory.search = _search;
Controller:
$scope.companies = function (val) {
var output = [];
var promise = serviceHelper.search('companies', val);
promise.then(function (result) {
result.data.forEach(function (company) {
output.push(company.companyName);
//output.push(company);
});
console.log(output);
}, function (error) {
adminInvoiceService.serviceErrorMessage(error);
});
return output;
}
Thanks!
Ok, I fixed it!
For all with the same problem here is my solution!
$scope.companies = function (val) {
return $http.get('http://localhost:5569/api/companies/search/'+val).then(function (res) {
var companies = [];
console.log(companies);
res.data.forEach(function (item) {
companies.push(item);
});
console.log(companies);
return companies;
});
};

deferred.resolve() is not iterating the last element inside a forloop

in the model.findone i'm getting a array which consists of 3 elements. In the else part i'm looping through each item & fetching offering head of that particular item.
But i'm able to get only 2 offering heads.Not able to fetch the last offering head.
Is there any problem with my code??
function getOfferingsHeads(id) {
var deferred = Q.defer();
var offeringHeads = [];
model
.findOne({ _id: id })
.exec(function (err, item) {
if(err) {
console.log(err);
deferred.reject(err);
}
else {
// deferred.resolve(item.offerings);
// var offeringsList = [];
// offeringsList = item.offerings;
for (var i = 0; i < item.offerings.length; i++) {
executivesModel
.findOne({offName: item.offerings[i] })
.exec(function(err1, item1) {
if(err1){
console.log(err1);
deferred.reject(err1);
}
else{
offeringHeads.push(item1.offHead);
deferred.resolve(offeringHeads);
}
});
}
}
});
return deferred.promise;
}
You can't resolve a deferred more than once, and in general you shouldn't be using deferreds at all. Since mongoose has a promise-friendly API, you should just use that. It will make your code much much cleaner:
function getOfferingHead(offName) {
return executivesModel
.findOne({offName: offName })
.exec()
.then(function (item) {
return item.offHead;
});
}
function getOfferingsHeads(id) {
return model
.findOne({ _id: id })
.exec()
.then(function (item) {
return Q.all(item.offerings.map(getOfferingHead));
});
}
To use the function:
getOfferingsHeads('myId').then(function (heads) {
console.log(heads);
});
Not sure this is what you intended but you are resolving the same promise more than once.
The latest version of mongoose lets you set the Promise library to use.
Here's a correction to what I believe you meant to do:
//Somewhere near mongoose definition
mongoose.Promise = require('q').Promise;
function getOfferingsHeads(id) {
var offeringHeads = [];
return model
.findOne({ _id: id })
.then(function (item) {
if(!item) {
//Handle no results
return Q.reject()
}
else {
return Q.all(item.offerings.map(function(offering){
executivesModel
.findOne({offName: offering.name})
}));
}
});
}
//Now you can use
getOfferingsHeads('someId').then(function (offerings) {
...
});

Delay loading data in Angular JS

I have code like this
(function (app) {
app.controller('productListController', productListController)
productListController.$inject = ['$scope', 'apiService', 'notificationService', '$ngBootbox', '$filter'];
function productListController($scope, apiService, notificationService, $ngBootbox, $filter) {
$scope.products = [];
$scope.page = 0;
$scope.pagesCount = 0;
$scope.getProducts = getProducts;
$scope.keyword = '';
$scope.search = search;
$scope.deleteProduct = deleteProduct;
$scope.selectAll = selectAll;
$scope.deleteMultiple = deleteMultiple;
function deleteMultiple() {
var listId = [];
$.each($scope.selected, function (i, item) {
listId.push(item.ID);
});
var config = {
params: {
checkedProducts: JSON.stringify(listId)
}
}
apiService.del('/api/product/deletemulti', config, function (result) {
notificationService.displaySuccess('Deleted successfully ' + result.data + 'record(s).');
search();
}, function (error) {
notificationService.displayError('Can not delete product.');
});
}
$scope.isAll = false;
function selectAll() {
if ($scope.isAll === false) {
angular.forEach($scope.products, function (item) {
item.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.products, function (item) {
item.checked = false;
});
$scope.isAll = false;
}
}
$scope.$watch("products", function (n, o) {
var checked = $filter("filter")(n, { checked: true });
if (checked.length) {
$scope.selected = checked;
$('#btnDelete').removeAttr('disabled');
} else {
$('#btnDelete').attr('disabled', 'disabled');
}
}, true);
function deleteProduct(id) {
$ngBootbox.confirm('Are you sure to detele?').then(function () {
var config = {
params: {
id: id
}
}
apiService.del('/api/product/delete', config, function () {
notificationService.displaySuccess('The product hase been deleted successfully!');
search();
}, function () {
notificationService.displayError('Can not delete product');
})
});
}
function search() {
getProducts();
}
function getProducts(page) {
page = page || 0;
var config = {
params: {
keyword: $scope.keyword,
page: page,
pageSize: 20
}
}
apiService.get('/api/product/getall', config, function (result) {
if (result.data.TotalCount == 0) {
notificationService.displayWarning('Can not find any record.');
}
$scope.products = result.data.Items;
$scope.page = result.data.Page;
$scope.pagesCount = result.data.TotalPages;
$scope.totalCount = result.data.TotalCount;
}, function () {
console.log('Load product failed.');
});
}
$scope.getProducts();
}
})(angular.module('THTCMS.products'));
So my problem is when i loading data the application take me some time to load data.
I need load data as soon as
Is the any solution for this?
Since you are loading data via api call, there will be a delay. To handle this delay, you should display a loading screen. Once the data is loaded, the loading screen gets hidden and your main screen is visible. You can achieve this using $http interceptors.
See : Showing Spinner GIF during $http request in angular
The api-call is almost certainly causing the delay. Data may be received slowly via the api-call so you could display any sort of loading text/image to notify the use that the data is being loaded.
If u want the data ready at the time when controller inits, u can add a resolve param and pass the api call as a $promise in the route configuration for this route.

error performing a get request

I am trying to perform a get request, in the post request everything is OK, I can see that in the post request all I do it's been save, once I refresh the page I am printing in the console the items saved by the post request, but those items aren't been return with the get I am doing.
here is where everything begins, I have a list of items here with the option to checked or unchecked the items in the list
<ion-item ng-repeat="sport in sports" ng-click="toggleSportSelection(sport)">
{{:: sport.name}}
</ion-item>
all the items are checked = true by default, so what I am saving, are the items with checked = false, the items checked = true you can see them here
<div ng-show="sport.checked" ng-repeat="sport in sports">
{{sport.name}}
</div>
this is what I have in the controller
.controller('SportsController', function($scope, SportsFactory) {
SportsFactory.getSportChecked(customer).then(function(sportChecked) {
_.each(sports, function(sport) {
var sportIds = _.pluck(sport, 'id'),
intersectedSports = _.intersection(sport.id, sportChecked),
checkedSportObjects = _.filter(sport, function(sportObj) {
return _.includes(intersectedSports, sportObj);
});
_.each(checkedSportObjects, function(sport) {
$scope.sports.push(sport);
});
});
}, function(err) {
console.log(err);
});
$scope.toggleSportSelection = function(sport) {
var params = {};
params.user = $scope.customer.customer;
params.sport = sport.id;
sport.checked = !sport.checked;
SportsFactory.setSportChecked(params);
};
// this is what puts the sports on checked = true
if (sports.length) {
$scope.sports = _.map(sports, function(sport) {
sport.checked = true;
return sport;
});
}
and this is the service / factory
.factory('SportsFactory', function($http, $q, AuthFactory,
LocalForageFactory, CONSTANT_VARS) {
return {
getSportChecked: function(customer) {
var defer = $q.defer(),
user,
rejection = function(err) {
console.log(err);
defer.reject(err);
};
LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED)
.then(function(sportChecked) {
user = customer.customer;
if (!_.isNull(sportChecked)) {
defer.resolve(sportChecked);
}else {
$http.get(CONSTANT_VARS.BACKEND_URL + '/sports/getChecked/' + user)
.success(function(sportChecked) {
LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_CHECKED, sportChecked);
defer.resolve(sportChecked);
})
.error(rejection);
}
}, rejection);
return defer.promise;
}
});
I am working along with NodeJS, so if you want the code I have in that part just let me know, so far I think that the issue I have is in the front end part, in the controller.

Resources