Angular update view without refreshing the page - angularjs

I was updating my view by refreshing the page. I know that there is a better way. Can someone show me how to update the view data without refreshing the page:
myApp.service("deleteService", function ($http) {
this.removeRow = function (recId, compName, custName, docName) {
$http.post('DeleteRecord', { settingID: recId,companyName: compName,customerName: custName, documentName: docName } )
.success(function (data, status, headers, config) {
window.location.reload();
})
.error(function (data, status, header, config) {
});
}
});

Without seeing the rest of your code it is hard to be able to give you an exact answer, but I'm going to assume you have a service to get your data.
Approach 1) You can inject your "getService"? into this service and access the function you use to retrieve the data initially.
Approach 2) Instead of having a seperate service for each CRUD function, you can have a CRUD service that will manage the data manipulation, this way you can just call the "get" function without injecting a seperate service.

Related

Passing same parameter, multiple times in same query to Rest service using $resource

I am consuming this Rest web service from my AngularJS application and I'm using $resource to pass parameters and get my data.
I have a particular service that can take the same parameter multiple times like this in my Postman session:
/myService/Accounts?acctId[]=7029&acctId[]=3324
I've tried to pass a generated string to my $resource query methods placeholder but it ends up escaping all my brackets and not working.
I also tried not using a placeholder and passing the same parameter twice, it doesn't fail but it takes the last value so that does not work either.
$scope.resultsColl = rfpService.searchAccountName.query({
acctName: $scope.accountName,
acctRole: acctRoleParams,
acctRole: acctRoleParams2
});
Hopefully someone has had this same issue? Any ideas?
From the research I've done on other posts it looks like you can't dynamically generate using $resource. My working solution was to switch to $http, this way I could dynamically generate multiple acctRole[] params:
var acctRoleParams = '';
if(corporate === true)
{
acctRoleParams = '&acctRole[]=C';
};
if(smallBiz === true)
{
acctRoleParams += '&acctRole[]=B';
};
$http.get("https://myRestServiceUrl/services/customer/accounts?acct=" + $scope.account + acctRoleParams)
.success(function (data, status, headers, config) {
$scope.gridOptions.data = data.data.detailsByAcct;
})
.error(function (data, status, headers, config) {
showToast("An error occurred during the request");
})
.finally(function () {
$scope.isGridLoading = false;
});
I wanted to post this in case anyone else has been struggling to do the same thing.

How to Prime $http $cache with AngularJS

When a user logs into the main page of my site, I typically load quite a bit of data on the home page. much more than when they come to a specific url on the page. When they hit the ome page, that actually fullfills the data requests of much of the data that I grab individually when they hit a specific page.
I like how the $http module works with $cache and I'm wanting to use the knowledge of my home page hit to populate the cache of calls I know the individual page will make.
That is, as an example, my home page calls /rest/clients which returns all clients while individual pages call /rest/client/101. What I want to do is make it so that if /rest/clients is called first, then when /rest/client/101 is called an new fresh xhr call does not have to be made but the data can be gotten from the cache as if /rest/client/101 had already been called.
I've never done a decorator before but I'm thinking maybe a decorator on the $http service? I looked through the $http code and it seemed the cache is stored in closure to the actual http call and not exposed except on the next Get.
Has anyone done this or similar? I could not find it. Any specific pseudo coding suggestions would be very welcome.
In your data service you have 2 methods, getAll and getOne.
In the service define a reference to your getAll results promise.
Then in your getOne service check to see if that promise exists and if it does use it to filter out the one item that you need to satisfy your getOne need.
module.service('dataService', function($http){
var getAllPromise = null;
this.getAll = function(){
if (getAllPromise !== null){
getAllPromise;
}
getAllPromise = $http.get('clients');
return getAllPromise
};
this.getOne = function(id){
if (getAllPromise !== null){
return getAllPromise
.then(function(allData){
//logic here to find the one in the full result set
return theFoundItem;
};
}
return $http.get('clients/' + id);
};
});
I found the solution I asked for but implementing and making it testable is proving to be beyond my skills. I'm going to go with #brocco solution but for the permanent record I'm leaving the actual answer to what I was asking. I'm not marking this as the correct solution because #brocco solution is better for my real problem. So, thank you #brocco for the help.
You can see below what I'm basically doing is to create my own $cache with $cacheFactory. I then use the .put method of the new cache object to prime my cache. Then, subsequent calls to the client/1 url will get the cache'd record without ever having to call cache/1 in real live. The cache is loaded in the for loop from the first big call.
Thanks for everyones input on this.
var myApp = angular.module('myApp', []);
myApp.factory('speakersCache', function($cacheFactory) {
return $cacheFactory('speakersCacheData');
});
myApp.controller('personController', ['$scope','$http','speakersCache', function ($scope,$http,speakersCache) {
$scope.getAllSpeakers = function() {
$http.get('speakers.json',{cache: speakersCache}).
success(function (data, status, headers, config) {
debugger;
var i;
for(i=0;i<data.length;i++) {
var url = 'speaker/' + i;
speakersCache.put(url, data[i]);
}
}).
error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
$scope.getAllSessions = function() {
$http.get('sessions.json',{cache: speakersCache}).
success(function (data, status, headers, config) {
debugger;
}).
error(function (data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
$scope.getOneSpeaker = function() {
$http.get('speaker/1',{cache: speakersCache}).
success(function (data, status, headers, config) {
debugger;
}).
error(function (data, status, headers, config) {
debugger;
});
}
$scope.checkit = function() {
var x = speakersCache;
debugger;
};
}]);
If I understand you well, I have done something similar:
I have this code:
.factory('myOwnEntity', ['$filter',
function ($filter) {
var myOwnList = [];
return {
set : function (data) {
myOwnList = data;
},
get : function () {
return myOwnList;
},
find : function (id) {
return $filter('filter')(myOwnList, { itemId : id }).pop();
}
}
}
])
When I make the petition to the Web Service, I store the information like this:
$http.get(url, {
cache : true
})
.success(function (data) {
myOwnEntity.set(data);
defer.resolve(data);
});
return defer.promise;
Now, the next time I need some information, I just query my entity with the find method. Hope this is what you are looking for.

how to pass large amount of data when exporting to excel using angularjs and web api

I am using angularjs + web api for my website.
I need to export a table to excel. I tried to use different JS methods, it worked on chrome but I also need it to work on >IE8.
So, I decided to use the server: send my table's $scope.data to server using post.
this is how it looks:
function excel_service($http) {
var _$http = $http;
self = this;
self.ExportToExcel = function (excel_data) {
var promise = _$http({
method: "POST",
url: 'api/ExportToExcel',
data: { "ExcelData": excel_data }
}).success(function (data, status, headers, config) {
}).error(function (data, status, headers, config) {
});
return promise;
};
};
when I debug, I see that part of the data appears in the request, but then, there is an error...
I think it's because I am trying to pass about 700 rows using that method.
Is there a way to send large data via post, or perhaps my approach is wrong, and It's better if I saved the data in server's session when it was retrieved, and then export it to excel from there.
Thanks.

Pass Angular Model to SailsJs

I trying to pass a form via $http.post from AngularJS to Sailsjs
My Sails Controller
create: function(req, res) {
console.log("req: "+req.param('user.firstName'));
res.send(req.param('user.firstName'));
},
My Angular Controller
function RegisterController($scope, $http) {
$scope.submit = function(){
console.log($scope.user.firstName); // works fine so far
$http.post('/user/create', $scope.user)
.success(function(data, status, headers, config) {
console.log("success");
})
.error(function(data, status, headers, config) {
console.log("error");
});
}
}
If I call my sails function like so /user/create?user.firstName=myFirstName its works fine. But if I try to read my passed data if I pass from angular. I don't know. I can't read the parm...
Someone any idea or a small example?
Cheers awesome community =)
You're posting the $scope.user object to your route, so it won't be namespaced under user. If the $scope.user contains, for example:
{firstName: "John", lastName: "Doe"}
then they would be available in your controller action as req.param('firstName') and req.param('lastName').
If you were to post the entire $scope object to /user/create (don't do this!), then you would be able to access req.param('user').firstName, req.param('user').lastName, etc. You still wouldn't be able to access things like req.param('user.firstName'), though; those are Angular expressions but they don't work server-side.

Angular.js - How to pass data from controller to view

This is the first time i am using Angular.js. So my workflow could be wrong.
How do i pass data from controller to the view
ng-view -> Displays html page using jade
When user clicks on submit button, i use $http on the controller and submit the request to the server.
The server returns me the necessary data back which i need to pass to another view.
My code snippet
function TrackController($scope,$http,$location,MessageFactory){
$scope.message = MessageFactory.contactMessage();
$scope.submit = function () {
var FormData = {
'track_applicationid': $scope.track_applicationid,
'track_email': $scope.track_email
}
$http({method: 'POST', url: '/track', data: FormData}).
success(function(data, status, headers, config) {
$scope.registeredDate = 'data.REGISTERED_DATE';
$scope.filedDate = data.FILED_DATE;
$location.path('trackMessage');
}).
error(function(data, status, headers, config) {
console.log('error');
});
}
}
In the above code, i want to pass registeredDate and filedDate to trackMessage view.
After going through the comments, i understood you are using one controller for two views.
If you want to set values to $scope.registeredDate and $scope.filedDate, You have to declare those objects globally using root-scope(Not recommended) or
use Angular values.
I recommended to use two different controllers.

Resources