Angularjs How can i post/put/delete data into local json file? - angularjs

Angularjs How can i post/put data into local json file?
To get data, i do:
App.factory('serv', ['$http', function ($http) {
var data = {};
db.getdata = function(){
return $http.get('data/album.json');
}
return data;
}])
I dont know how to do for POST , PUT and DELETE.
Is it possible?

You can try this useful Angular API : https://github.com/mgonto/restangular
if you want to manage data saved in a json file then you can use this JSON server : https://github.com/typicode/json-server

You can write to local files with JavaScript using the HTML5 file system API. Check here: http://caniuse.com/#feat=filesystem to see if it's supported where you need to use it.
If you are able to use it, then you would simply write out a new JSON file in its entirety when you want to persist your data. You can read about the file system API here: https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Introduction
If your needs are more than just a simple JSON document you might want to check out indexeddb as well.

Related

http.get doesn't work inside a for loop when fetching data from mongo using express

I am trying to fetch data from mongodb using express to angular inside a for loop.
I can access data inside this get instance but not outside of it. Here is my code
var daily_jobs=[];
$http.get(mongodUrl).then(function(response) {
var allMachinename = response.data;
daily_jobs=[];
for(var i = 0;i<allMachinename.length;i++){
$scope.masch_name.push({name:allMachinename[i].name,id:allMachinename[i].id,daily_jobs:[]});
$http.get(mongodUrl+'getmaschdata/'+$scope.input_id+'/'+allMachinename[i].id).then(function(jobs) {
if(jobs.data.length > 0){
daily_jobs= jobs.data;
}
console.log(daily_jobs[0].job_name);
},function(err){
console.log(err);
});
$scope.masch_name[i].daily_jobs= daily_jobs;
}
},function(err){
//console.log(err);
});
The variable daily_jobs is global, but when I want to access it outside the get function it always remain empty. How can I get that value outside of second http.get function? Any help will be appreciated. Thanks.
I couldn't get a clear picture what are you trying to achieve why are you making two http get inside a controller rather than making as a service. however to answer your question replace this
daily_jobs= jobs.data;
with
$scope.masch_name[i].daily_jobs = jobs.data;
that should work if you want to know more about this read here
Angular Share Variable betwen $http.get and controller
I will suggest you to read about services in AngularJS and $scope.apply as well for more detail

Store JSON file contents on load

Right now, I have a factory which loads a JSON file.
angular.module("app").factory("RolesFactory", ['$http', '$q', function($http, $q) {
var d = $q.defer();
$http.get('events.json').success(function(data) {
d.resolve(data);
});
return d.promise;
}]);
And then I call this factory when I need the contents of events.json with this controller:
App.controller('rolesCtrl', ['$scope', 'RolesFactory', function($scope, RolesFactory) {
RolesFactory.then(function(roleData){
$scope.roles = roleData.roles;
});
}]);
All good, but whenever I need to use this data. Isn't it refetching the contents of events.json? Meaning: is Angular reloading the file over and over again? I was hoping to load the file once and call it by a global variable or something.
When my app loads initially, I want it to load and store the contens of events.json -- and then I'd like my app to be able to use this data whenever/wherever.
Is this possible?
As AngularJS is a stateless framework, you have only a few options here, all of which are some kind of client-side caching:
Use localStorage to store your data. Once the data is fetched, you can just save it to localStorage using localStorage.setItem after Stringifying the JSON. You'll need to re-parse the JSON the next time you use it though, so if this is a giant JSON, this is not the best idea
Use sessionStorage to store your data. This is exactly the same as #1, but you will lose data upon termination of session,i.e. closing your browser.
Trust the JSON to be cached in your browser. This is most likely the case. Static assets are by default cached by most modern browsers. So, the second time your factory requests the JSON, the resource isn't actually fetched from the server. It is merely pulled from the browser's cache.
NOTE: The way to check this is to see what the HTTP status code for your resource is, in Chrome's Developer Tools Network tab. If the status says 304 that means it has been pulled from cache.

Preload AngularJS partials used in routes?

Question: What is the best way and the best time to pre-load .ng files that are used in routing templates?
In researching this thus far, I've found the following answers:
Use Angular's script directive.
Problem: My content cannot be loaded as a literal string but needs to be fetched from the server. In other words, I have an .ng file as my partial so I cannot do
my content must remain in a .ng file on the server and be fetched
Use $templateCache.put to put a template literal in the cache. Same problem as above.
Use $http to load the .ng file. This works in that it is not a string literal but I am struggling to find the best time to perform this so that it is not blocking (realize its async but still)
To save you from suggesting resources I've already seen, I've read the following:
Is there a way to make AngularJS load partials in the beginning and not at when needed?
https://groups.google.com/forum/#!topic/angular/6aW6gWlsCjU
https://groups.google.com/forum/#!topic/angular/okG3LFcLkd0
https://medium.com/p/f8ae57e2cec3
http://comments.gmane.org/gmane.comp.lang.javascript.angularjs/15975
Maybe use a combination of 2 and 3.
Like you said, $http is async, so why not just put each partial into the templateCache after the app has loaded.
For example:
var myApp = angular.module('myApp', []);
myApp.run(function($http, $templateCache) {
var templates = ['template1.ng', 'template2.ng'];
angular.forEach(templates, function(templateUrl) {
$http({method: 'GET', url: templateUrl}).success(function(data) {
$templateCache.put(templateUrl, data);
});
});
});
I've never had the need for this and definitely haven't tested it, but the idea is there.

How to refresh local data fetched using $resource service in AngularJS

I have AngularJS application that use $resource service to retrieve data using query() method and create new data using model.$save() method. This works fine exactly as the docs say it should.
My question is how to update my local data fetched using MyService.query() in the first place after I've changed it?
I took the most simple approach for now and I simply call the query() method again. I know this is the worst way efficiency-wise but it's the simplest one.
In my server-side I return the whole state-representation of the new model. How can I add the newly created model to the array of the local data?
UPDATE
I've end up simply pushing the model return from the server but I'll still be happy to know if that's the way to go. From what I can understand from the source code the return array is plan-old-javascript-array that I can manipulate myself.
This is the code I used
$scope.save = function () {
var newComment = new CommentsDataSource();
newComment.Content = $scope.todoText;
newComment.$save({ id: "1" }, function (savedComment) {
$scope.comments.push(savedComment);
});
}
I would simply get the whole list again, to be able to see the modifications brought to the list by other users.
But if the solution you're using suits you, then use it. It's corrrect. Angular uses bare-bones JavaScript objects. Adding a new instance to a list in the scope will refresh the list displayed on the page.

How to Store json data file in a services using angularjs

Just want to know your idea wht will be my approach on how to store external json data file into a services so that i can inject it into different controllers
Thanks
Try to use ngTranslation module.
with this service you can store the static content(some json file, etc..) outside of the code, and not dirty your controllers/services...
EXAMPLE:
JS:
angular.module('app', ['ng-translation'])
.config(['ngTranslationProvider', function(ngTranslationProvider) {
ngStaticProvider
.setDirectory('/assets/static')
.setFilesSuffix('.json')
.langsFiles({
demo1: 'demo1',
demo2: 'demo2'
})
}]);
//inject to controller
function PanelController($scope, translateFilter) {
$scope.panelContent = translateFilter('key','fileName')
}
HTML:
<!-- use as a filter {{ key | translate: fileName }}-->
<p>{{ key | translate: fileName }}</p>
<!-- use ng-translate directive, similar to ng-bind-->
<p ng-translate="file(key)"></p>
Well, it all depends on the architecture of your application but I guess you could create a factory or service that will store data then simply inject that factory wherever needed.
If the data needs to be persistent, I would use something like localStorage. If it's a really small amount of data and your app cannot support HTML5, I would use cookies.
The more you elaborate the more accurate answer you will get.
Have look at the angularjs tutorial. It specifically address this issue.
First go though http://docs.angularjs.org/tutorial/step_05 where you include the json in controller.
Then follow http://docs.angularjs.org/tutorial/step_11 where it is moved to service.
$http.get() can be used to retrive data from REST urls as well.

Resources