Reload all the app after upload in AngularJS - javascript

I'm doing a quite large app that needs to save a Javascript object and save it to client's disk and viceversa: retrieve JSON object and parse it.
I've managed to save and upload the file, but here's the problem: When the file is successfully uploaded (checked from the console and inspector), Angular does not display anything at the ng-repeats, ng-model...
I assume the problem is that Angular does not know that the object has changed. I am wondering, since I seem not to find it anywhere: how can I re-render all of my Angular app?

What we did in one of our Angular projects, is some kind of 'cacheId'.
So imagine simple POST service generating random integer number.
Imagine another GET service returning that number.
Now in your Angular templates, wherever you specify template rul name, add 'cacheId' as param.
Instead oF that:
templateUrl: 'some-folder/some-template.tpl.html'
Do that:
templateUrl: 'some-folder/some-template.tpl.html?cachedId=' + someService.cacheId
What advantage?
You can click resetCache() url and generate different cacheId
client will get different cacheId in next request
browser will treat html template url as new url and will reload template
by reloading template you will get new data in
Something like that might work.

Related

Cache API with MVC Views

I have a basic MVC form and I've been trying to use the Javascript Cache API to cache all my css, js, html files so that when users (people in the field) do not have reliable access, they can still use my web form. Obviously I'm using IndexedDB and service workers as well to check for a connection and save locally when a connection is not available, syncing when it is available.
I've gone through some tutorials and everything seems straightforward when dealing with caching actual, physical files (css, html, js). MVC is weird though since you're routing. I created the basix Index, Create, Edit, Details views. When I create an array of URL's to cache such as
var urlsToCache = [
'/App/Details',
'/App/Edit',
'/App/Create',
'/App/Index',
'/App/Content/bootstrap.css',
'/App/Content/site.css',
'/App/Scripts/jquery-1.10.2.js',
'/App/Scripts/jquery.form.js',
'/App/sw.js',
'/App/Scripts/bootstrap.js',
]
.. everything caches except for DETAILS and EDIT. Index and create cache fine. I'm actually surprised the latter two cache at all since they aren't physical files. I'm assuming Details and Edit don't cache because they don't work without querystring parameters.
Is it POSSIBLE to cache these two views at all? Or does anyone know of anything on NuGet that addresses this situation?
I changed this in the GET method for my Edit action to return an empty Model if there was no ID
if (id == null)
{
//return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
return View();
}
This allowed me to load the Edit page without a querystring variable and not get an error message. The page loads with no data but it allows me to cache it. At this point I suppose I would have to tell my service worker to check if the page is online. If it is, route the request normally, else query the local storage and manually plug the values into the fields.
So let this be a lesson to anyone creating Offline-enabled apps with MVC and using Cache API. Get rid of the lines that return bad request errors in your CRUD views if ID numbers aren't passed. Just pass back a blank model to the view (return View()). This allows you to cache your pages. And you'll obviously need to write code to handle the offline retrieval and presentation in code that executes when the page loads, but it will still allow you to utilize the MVC/Razor features when online.
One thing to note: "/App/Edit" will cache. If you load "/App/Edit/2", it won't match a url in your cache so you'll get an offline message. However, you can easily modify your Index page to send the ID via post. Just have a form on the page that goes to the Edit action and change the link to an underlined span with an onclick that sets the value of a hidden field to the ID. You'll have to pass another hidden field to let it know that it needs to retrieve instead of update (since the controller has different GET AND POST actions for Edit. The GET action is useless, but keep it for caching. You're retrieval that you normall would do int the GET is now going to be done in the POST with an if statement to check for your hidden field flag.

How to take user to a specific landing page using angularjs?

I am trying to replace an existing application with a new angularjs application. In existing application user comes to a specific landing page from external app through a specific url something like
'localhost:8080/APP_NAME/recordPage?recordId=ABC123'.
I am trying to implement new app using angularjs. I managed to build app to access
'localhost:8080/APP_NAME/#/recordPage?recordId=ABC123'
using angular routing mechanism. But is it possible to make url available exactly as it was before with out '#/'?.
In spring framework i can define it in controller to return to landing page directly, but is it even possible in angularjs to directly access specific page without going home page or index page?
localhost:8080/APP_NAME this is your context path and in angularJs '#' differ context path with specific accessing path.
So when ever you want to access another page it simply change the path after #, so it is easy to set state with particular url.
& if you don't want to go through '#' then don't declare your file path in index page and access it from outside.
This is resolved by creating a separate servlet to handle direct access using servlet annotations
'#WebServlet("/recordPage")'

Javascript function not getting called properly in Angular JS

I am basically building a form for my project.
Here is plunkr URL for the project: https://plnkr.co/edit/FNx7t48XFOJHrFzIpd1R?p
MainController.js: This has a factory called FormDataService which tracks user's input into the form and saves the data to Angular's front-end model in real time.
129.html: This is the view where question lives on.
Sample.json: I use this format of json files to feed the view for 129.html
129Ctrl.js: Just a controller
app.js: I define the routes for views using ngroutes
In my 129Ctrl.js, I'm adding $scope.formData = {};. This lets me to save what user inputs into formData. The problem is that when the user refreshes, the formData does not persist. FormDataService in MainController.js is supposed to do that work, but I'm not sure why it isn't doing it.
when the user refreshes the page your controller is initialized again
and all your declared variables and scopes are reset.
if you want to use Angular's front-end model in real time you can use $localStorage or $sessionStorage from this repo
there are other repositories as well.
this way data will persist during the life time of your application,
even when user refreshes the page.

Alternative to passing Data to JavaScript from PHP?

I have a fairly large Application and I'm currently trying to find a way around having to pass Data from PHP (User Tokens for 3rd Party API's and such) through the DOM. Currently I use data-* attributes on a single element and parse the Data from that, but it's pretty messy.
I've considered just making the contents of the element encoded JSON with all the config in, which would greatly improve the structure and effectiveness, but at the same time storing sensitive information in the DOM isn't ideal or secure whatsoever.
Getting the data via AJAX is also not so feasible, as the Application requires this information all the time, on any page - so running an AJAX request on every page load before allowing user input or control will be a pain for users and add load to my server.
Something I've considered is having an initial request for information, storing it in the Cache/localStorage along with a checksum of the data, and include the checksum for the up-to-date data in the DOM. So on every page load it'll compare the checksums and if they are different (JavaScript has out-of-date data stored in Cache/localStorage), it'll send another request.
I'd rather not have to go down this route, and I'd like to know if there are any better methods that you can think of. I can't find any alternative methods in other questions/Google, so any help is appreciated.
You could also create a php file and put the header as type javascript. Request this file as a normal javascript file. <script src="config.js.php"></script> (considering the filename is config.js.php) You can structure your javascript code and simply assign values dynamically.
For security, especially if login is required, this file can only be returned once the user is logged in or something. Otherwise you simply return a blank file.
You could also just emit the json you need in your template and assign it to a javascript global.
This would be especially easy if you were using a templating system that supports inheritance like twig. You could then do something like this in the base template for your application:
<script>
MyApp = {};
MyApp.cfg = {{cfg | tojson | safe}};
</script>
where cfg is a php dictionary in the templating context. Those filters aren't twig specific, but there to give you an idea.
It wouldn't be safe if you were storing sensitive information, but it would be easier than storing the info in local storage,

Make sure file.json is synched to BackBone Collection

I'm new to BackBone and building my app based off a template found on the web. I start by loading my data from file.json like so...
livestock.groups = Backbone.Collection.extend({
model: livestock.Activity,
url: "groups.json"
});
I then have several lines of code loading the collection to the HTML and setting button functionality. Then near the end I have a line which updates the extended collection like this...
function addToList(activity) {
livestock.groups.add({id: 6, type: activity, comments: 'Wow...that was easy.'});
}
This works fine for the HTML version of the collection but I want to add a line to addToList function that will update my .json file. How can this be done?
This isn't actually possible. Backbone was meant to interact with a RESTful web service. When you give it the URL to a JSON file like your'e doing, it sends a GET request, which works fine. It doesn't know whether or not it called a web service or not. However, when you want to send the update to the collection, it generates an HTTP POST request. However, that doesn't do any good submitting a POST request to a static file. Apache or whatever you're using to host the JSON file will probably ignore that and serve the static file again.
The real problem, however, is unrelated to Backbone itself. The problem is you can't edit a file on a remote server via javascript. You need some web service in between using something like PHP or Ruby that can take the request from Backbone and update the file on the server's hard drive.
If instead you're developing right now on your local computer, then this won't work for a different reason. Your browser, for security reasons, won't allow javascript to modify local files on your hard drive, even though they're in the same folder as your html and javascript.
Hope this helps.
Edit: Based on comments, adding links here to a couple sample adapters for Backbone to LocalStorage and IndexedDB:
http://documentcloud.github.com/backbone/docs/backbone-localstorage.html
https://github.com/superfeedr/indexeddb-backbonejs-adapter

Categories

Resources