not able to dynamically update the view when data is changing - angularjs

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.

Related

angularjs with <portlet:renderURL/> and spring mvc portlet

I have this code for my table :
##
<tr ng-repeat="elt in tabDemandes">
<td>{{elt.id}}</td>
<td>{{elt.name}}</td>
<portlet:renderURL var="maj">
<portlet:param name="action" value="maj"/>
<portlet:param name="idD" value="elt.id"/>
</portlet:renderURL>
</tr>
##
I want recover a value of my param "idD" in my controller but it take elt.id as a value of a param and he give me error
can someone help me ?
To have access to the idD in your controller just set a $scope that can hold it. Angularjs is built with 2-way data-binding in mind so really what this lets you do is make changes in the view that will go to the controller as well as changes in the controller being pushed out to the view.
In your case just make sure you are storing the idD as an ng-modle that links back to a scope you declared in the controller. Once you have that linked correctly you can get the idD in your controller no problem.
Obviously, the difference is that the JSTL taglib (<portlet:renderUR>L) runs on the server, while AngularJS and the ng-repeat runs on the client. At the moment AngularJS is looping over your content, the URL has already been rendered.
For more information about the differences of server- and clientside, look at this answer: What is the difference between client-side and server-side programming?
What we did was quite simple, we attached the URLs to our model (in your case tabDemandes). This is an example we used for creating an action URL with the ID as a parameter:
PortletURL detailURL = response.createActionURL();
detailURL.setParameter(ActionRequest.ACTION_NAME, "detailTask");
detailURL.setParameter("id", Long.toString(task.getId());
task.setDetailURL(detailURL.toString());
In this case we were using a list of tasks, and we used this action URL to open a detailed page of the task, so we had to pass the ID to the action URL. In stead of using the JSTL taglib we used the Java API.
In your case you'll probably need to use response.createRenderURL().

How does AngularJS handle Memory

I am wondering how AngularJS 'saves' its data/model. Does it actually save it or.. how does it work?
We are using different methods to retrieve JSON data. In other frameworks like jQuery we had to think about how to store data locally, i.e. when we want to provide a sorting possibility. In Angular this seems different, it seems to do all that for us out of the box.
Is it that Angular displays everything how it is supposed to be and looks at changes, reads in the displayed data in and then displays it differently or does it use a local storage to save the raw json.. and work from there? (This would limit the amount of data we can feed)
Here is a simple code-example:
$http.get("url-to-json")
.success(function(returnedData) {
$scope.search_result = returnedData['search_result'];
})
From there I can just use:
<div ng-repeat='result in search_results | sortResult:"price":sorted' id="res_<% result.id %>" class="result">
Product: <% result.name %>
</div>
I am riddled how Angular still knows the data and doesn't have to load it again from the external source.
Do you know?
There is a lot more that goes into it, but essentially its all stored in local memory. Angular creates an object of all your scope properties. When you do data binding in angular you are registering an event listener and when that event is called angular loops through this object detecting if something has changed, and if so updates the object accordingly. Each time an update occurs it returns to the loop to check if anything else has been updated. This is what is referred to as the $digestLoop.
SOURCE
The ng-book

AngularJS $resource management

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

Refreshing translations using angular-translate

I'm using angular translate for i18n.
The particular feature I'm working on is updating the status of a book. In the service callback, if successful, I am updating my book status from, say, Open to Closed. If I view the scope (using Batarang), I can see my DOM element as such:
<span translate="Closed" class="ng-scope">Open</span>
As you can see, the translate value is being updated, but the translation itself isn't occurring on its own. I've read the docs and understand this is expected behavior. What I want to know, though, is how should I be refreshing the translated value?
Presently, I'm injecting the $translate service and executing $translate.refresh() every time I update a scope value that needs to be re-translated. I feel like that's clunky, and probably not the way I should be doing it.
Any thoughts?
You definitely should not issue a refresh for this.
just do something like this:
<span> {book.state | translate} </span>
Given that your book model has a member state to reflect it's state.
Whenever the model changes, the value of state will be re-translated.
Create a common service for translation, this will configure our translation code, in particular it will configure the location of our translation files. Create a directory src/common/translation, and a file src/common/translation/translation.js:
http://technpol.wordpress.com/2013/11/02/adding-translation-using-angular-translate-to-an-angularjs-app/
angular.module('angularTranslateApp', ['pascalprecht.translate'])
.config(function($translateProvider, $translatePartialLoaderProvider) {
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: '/UI/assets/translation/{lang}/{part}.json'
}
});
$translateProvider.preferredLanguage('en-AU'); });

How to use $resource in AngularJS properly for building a client app?

I've been following this tutorial http://draptik.github.io/blog/2013/07/28/restful-crud-with-angularjs/. I implemented a Grails backend with it instead of the Java one in the tutorial.
I've got the data coming back and forth, with one issue. If I create/update/delete a user, I don't see the changes reflected on my user list when I am redirected back. I have to refresh the page to see the updates.
Looking at the network traffic for an edit, it looks like it does a PUT and fires off the GET before the PUT is complete. Assuming this is because $resource returns a promise so things can be done asynchronously. So how do I handle this so that when $location redirects me, my list is up to date?
I'm guessing the options are to wait for the PUT to complete before redirecting/querying for the list, or to somehow manually manage the $scope.users to match the request?
Or maybe this tutorial is just a bad example? Maybe there is a better way to do it (still using $resource)?
Note: I've seen Restangular out there, and I've seen $http with success callbacks, but I would like to understand the situation above.
One way to overcome this issue would be to not redirect to the list page, till you get a callback, and then do a redirect. You can show some busy indicator till that time. The resource call looks like this.
resource.update(config,data,function() { //gets called on success},
function(error) { //gets called on failure});
In real life scenario waiting for the response of update makes sense as you want to handle the error and success scenarios on the same page.
I don't see your code anywhere so i'm just assuming (based on what you wrote and your current problem)
You are probably doing a full (or partial) get each time you changed a user and (re)binding the result to your scope. Doing this in the callback of the resource should actually start the digest cycle angular does to update modified objects. If you had been doing the fetching outside $resource - for example with custom/jquery ajax you would need to execute $scope.$apply()
What i really don't understand you would need to wait for the callback. You already know you added/modified a user. Instead of 'detaching' that user from your scope, modify it, post it to your rest server, then wait for callback, and reinserting it into the scope - why not modify it directly in the list/array you put on your scope?
var users = Users.get(function () {
$scope.users = users.record; // bind the resulting records to the scope
});
$scope.updateUser = function (user) {
resource.update(...); //pseudo
};
Then in your html, you will keep a reference to the currentUser and the div-list will update automaticly.
<div ng-repeat="user in users" ng-click="currentUser=user">{{user.Name}}</div>
<input ng-model="currentUser.Name">
<button ng-click="updateUser(currentUser);">Update</button>
If you don't want to see the update in the list while you type, but only once your callback fires or when you hit the button, would would instead use another ng-model for your input like this:
<input ng-model="tempUser.Name">
And you would then copy the value other in either the updateUser method or in the resource callback like this:
$scope.updateUser = function (user) {
user.Name = $scope.tempUser.Name; // should update automaticly
resource.update(...) // pseudo
}
Hope it helped!

Resources