AngularJS $resource management - angularjs

I am trying to find a clean way to manage my $resource models in my application. I have some RESTful endpoints for a template model:
GET /api/templates/ //query all template
GET /api/template/:id // get single template by id
PUT /api/template/ // create a new template
PATCH /api/template/:id // update a template
DELETE /api/template/:id // delete a template
var TemplateResource = $resource('/api/templates/:templateId', {templateId:'#id'}, {
'create':{method:'PUT'}
})
I can simply run
var templates = TemplateResource.query(function(){
console.log(templates) // an array of template models
}
Once I have the list in memory, I use an Angular service to keep the list in state and consecutive calls just return the list rather then making the call again.
Now my question is regarding how to manage a single template. If the user goes to the "Edit Template" view, then saves the template I run template.$save() to run a POST on the template. The problem is that this template is seperate from the list that was pulled in from the query, so the list doesn't get updated in the UI.
Should I stem all my single template requests from my list of templates? (meaning I never actually call GET /api/template/:id, instead I just always find the template in the list)
OR
Should I just continue to run individual calls on the template, and when the POST request comes back, I just "update" the current list of templates with the updated model.
Let me know if I should provide more info about something

Related

Prevent Firebase $firebaseArray auto update

I am working on a News Feed that is similar to Facebook News Feed. I am implementing it in the following sequence:
When app is started, get everything, but only push two item to show.
The user can scroll down to see more and I will add more to the list.
If there are any new items, the user needs to pull to refresh to add the new ones.
The only problem I have right now is that each time an item is added, $firebaseArray automatically adds the new item to my array that I do not want snyc changes (I want to query once, get a set list). I was wondering if anyone would know how to prevent the auto update?
Look into .once this will allow you to get the data just once: https://firebase.google.com/docs/reference/js/firebase.database.Query#once
Instead of binding directly your $firebaseArray to the view, clone it to a scope (or controller) property that will be bound to the view. Factorize this process in a function you can call when the user pull-reloads so the the $firebaseArray is re-created.
A more appropriate approach would be to use Firebase's http api, with the angular $http service.
Edit: to clone the array to a scope var, try the following:
var allEvents = $firebaseArray(queryOfeverything);
allEvents.$loaded()
.then(function(events){
$scope.allEvents = angular.map(events, function(event) {
return event; // you may want to replace this line - I am not very familiar with firebase.
})
});

Passing Data vs. Separate Request in AngularJS using ngResource

I'm new to angular and trying to figure out how best to accomplish this.
Say you have set up an ngResource factory to get a bunch of widgets . You return those widgets(GET /api/widgets) and display them on the page in a list.
Now say you can edit those widgets in a dialog box by clicking an edit button next to the object in the list. Is it better practice to pass the individual widget's data (that was already retrieved by the first $resource call) to the edit dialog, or simply pass an ID parameter to the dialog box and have it resolve it's own $resource call using a separate GET /api/widgets/:widgetID call.
The data wouldn't realistically change between loading the list and clicking the edit button, so it doesn't need to be synced to the exact second. Both of these requests would come from the same factory, but the question is if you should store the data and pass it, or execute a separate request.
I don't see a reason to fetch it again, I would just reuse the object.

not able to dynamically update the view when data is changing

I have a set of files in a server which I am looping though and constructing a JSOn and saving it as a separate file. I am using python for this. Works quite well. Now the scope is the number of files in the directory will increase/ change throughout the day..and I am running the script every 10 min to rewrite the json...the file name stays same and i am calling it in a single page html document using angular.js..Again fairly simple...But now I am having problem when the JSON is changing I am not seeing any change on the page unless I reload the page. Could I do something about this?
With angular I am using
$http('something.json').success(callback function with some argument data)
and in the markup something like
<ul>
<li ng-repeat="x in data">{{x.id}}</li>
</ul>
Your call to $http is one-time operation which happens after page load like this:
$http('something.json').success(function(data){
$scope.data = data;
});
angular is kickstarted
ng-controller containing $http request is evaluated and request for 'something.json' is sent
...
when your json arrives, your success function is called with data from json
view (html template) is updated with new data
Angular keeps your model (eg $scope.data) and UI (expressions in template) up to date, but it doesn't update external resources.
If you want to periodically poll for changes in 'something.json'
you can use $timeout service as suggested in JaKXz's comment.

Angular CRUD, update view when backend/database changes ($resource and REST)

I am currently making an application in angular which does this:
(On page load) Make an api call in angular controller (to symfony2 end point) to get: items.
$scope.items = ItemsService.query(function(data){
$scope.loading = false;
}, function(err){
$scope.loading = false;
});
items is an array containing many item objects.
Each item contains parameters e.g. item.param1 item.param2.
I have built it in a similar way to this tutorial:
http://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/
i.e. The angular controller calls a service which calls the (symfony2) backend api endpoint.
The endpoint passes back items which is gets from a database. Items are then put into the view using ng-repeat (item in items).
This all works fine.
Now, I have a button (in the ng-repeat) which effectively causes a PUT request to be made to (another symfony2 endpoint), thus updating item.param1in the database. This also happens in the tutorial I linked to.
The problem is that (in my application and in the tutorial) I have to again make an api call which updates ALL the items, in order to see the change.
I want to just update the data in the view (immediately) for one object without having to fetch them all again.
i.e. something like:
$scope.items[4] = Items.get({id: item.id}, function(){});
Except the application array key isn't known so I cant do that.
(so something like: $scope.items.findTheOriginalItem(item) = Items.get({id: item.id}, function(){});.
Another possible solution (which seems like it may be the best?). I have looked here:
http://teropa.info/blog/2014/01/26/the-three-watch-depths-of-angularjs.html
And tried doing the equality $watch: $scope.$watch(…, …, true);. Thus using watch to see when the item sub-array is updated. This doesn't seem to update the data in the view though (even though it is updating in the database).
Any advice on the best way of doing this (and how to do it) would be great! Thanks!
Essentially the button click should use ng-click to execute a function and pass the item to that function. Example:
...ng-repeat="item in items"...
<button type="button" ng-click="updateItem(item)">Update</button
...
Then in the function you have the exact item that you want to update. If you are using $resources, it would be something like:
$scope.updateItem = function(item) { item.$update(...); };
Unless I didn't understand you

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.

Resources