Using JSON response in more than one controller with angularjs - json

My website is a posting site with posts from different countries. On homepage load i will make a service call and get all the posts using a controller($http) and will be displayed on the homepage.
In the homePage two dropdown and a button are given from which user can choose or filter the posts by country and theme, and results will be in different page.
I want to use the same controller response data without making a new service call to filter the response and show the results.
Please help me on how can i use the same controller or do i need to use a factory and then make the factory as a dependent to my controller??

The best way to do that is to do with a Service. Service is a Singleton, which means that construction will happen only once. In Service constructor you will load posts, and the from any controller you can access your data.
angular.module('myApp').service('myPostService', function($http) {
var Service = {
postList: []
};
// Here load over $http service your posts and then put it into Service.postList.
return Service;
});
Then inject the service and use the posts
angular.module('myApp').controller('HomeCtrl', function(myPostService) {
$scope.postList = Service.postList;
});
And in HTML iterate over it, filter and do whatever you want.

Related

Page expiring while trying deleting created APIs

I am creating my data API using the Laravel Resource. And testing the methods in Postman. Now when I am trying to fetch data from database and show them, it is working fine both in Postman and Browser.
But when I am trying the delete method, using postman, providing the URL as per I defined in my routes and selecting the method delete, it returns me:
"419 Page Expired"
Here is my route for delete:
Route::delete('feed/api/{id}', 'FeedController#destroy');
Here is the function in controller:
public function destroy($id)
{
$feed = Feeds::findOrFail($id);
if ($feed->delete()) {
return new FeedResource($feed);
}
}
Note: If I use the route in my api.php file instead of web.php, it works. But I don't want to keep that in api.php. Because the routes in api.php don't work if middleware checked.
For api you must exclude routes from csrf check for apis in VerifyCsrfToken.php

PUG with javascript

If I have the following piece of code
script.
function getProductParams(params) {
return JSON.parse(localStorage.getItem(params));
}
each product in products
-var getVariable = getProductParams("ids");
This piece of code doesn't work, I'm guessing that - is on server side, while script. is on clients?
How can I access a variable from localStorage in pug and use it for comparison with variables received from server.
I want to make something like this
script.
function getProductParams(params) {
return JSON.parse(localStorage.getItem(params));
}
each product in products
-var getVariable = getProductParams("ids");
-if (getVariable.includes(#{product._id}) {
// create the element in html
-} else {
- // call next product and compare if we have it
-}
The simple answer is that you can't do this. LocalStorage is exactly that - local. Your server can't directly access it unless you explicitly pass it back using some other format/method.
What your server can access easily is the cookie. If you store the data in the cookie and use cookie-parser then you can handle this list quickly. This use case is exactly why cookies exist.
Another option would be to pass the data to the server in the body of a POST request, but your question doesn't provide a lot of information as to what exactly you're doing and if this is an option or not.
It would also be much easier for you to accomplish all of the sorting and filtering in your route instead of the pug template. That way you have full request to the cookie, request body, etc. directly and you don't have to pass that down to the template too.
Then, when your template gets the list it's a really simple matter to render it:
each product in products
//create the element in html

AngularJs - passing parameters from grid result rows to external webpage

I am working on a webapp built upon angularjs.So,i have a search result UI built which upon search displays result in grid.Now,when user clicks on each row of the result ,an external webpage should be called with values of columns passed from that clicked grid row to the external webpage.
How can i do this,can i have a sample controller to refer upon.
Please help with this
Thanks,
Alex
If I understand you correctly, you want to send an AJAX call to some JSON api when a user clicks on some element. Here's a basic thing of how to do that in an angularjs controller:
angular.module("your.app")
.controller("ajaxingCtrl",["$http","$scope", function($http, $scope){
$scope.onSomeUserAction = function(argument){
//substitute the type of request your api requires
$http.get("http://your.remote.api/some/resource",
{
//params will get parsed into HTTP query parameters
params: {
x:arguments.x
}
}
).then(function(result){
console.log(result);// and then do what you will with the result
})
}
}])
You can find more information about doing ajax calls in angular's $http service docs.

All data is gone on page reload. Is there any way to avoid that?

I have developed one dashboard application in angular js which is having search functionality and multiple views with lots of different data coming from that search functionality.
Its single page application. So I am facing issue on page reload all data is gone and it shows view with blank data.
Is there any way to solve this issue or any language which help me to create single page application and maintain same data on page reload??
Any suggestion will be appreciated.
Search Page
Data after search
Data after reload
You can use sessionStorage to set & get the data.
Step 1 :
Create a factory service that will save and return the saved session data based on the key.
app.factory('storageService', ['$rootScope', function($rootScope) {
return {
get: function(key) {
return sessionStorage.getItem(key);
},
save: function(key, data) {
sessionStorage.setItem(key, data);
}
};
}]);
Step 2 :
Inject the storageService dependency in the controller to set and get the data from the session storage.
app.controller('myCtrl',['storageService',function(storageService) {
// Save session data to storageService on successfull response from $http service.
storageService.save('key', 'value');
// Get saved session data from storageService on page reload
var sessionData = storageService.get('key');
});
You need to save data before changing the state of application / moving to another page,route.
So, either save that data using
Angular services (Save data, change route, come back check the data in service and reassign variables from service.)
Local-storage to save data. (Save data, change route, come back check the data in service and reassign variables from service.)
Rootscope. Set data in rootscope and move .. after coming back check the variables and reassign.
Your problem is not saving the data, but saving the state in your URL. As it is, you only save the "step", but no other information, so when you reload the page (refresh, or close/re-open browser, or open bookmark, or share...) you don't have all the information needed to restore the full page.
Add the relevant bits to the URL (as you have a single page app, probably in the fragment identifier). Use that information to load the data, rather than relying on other mechanisms to pass data between the "pages".
Get data on page refresh, that is something like,
$rootScope.on('onStateChangeStart', function(){
// here make a call to the source
$http(); // request and try to get data
})
use localStorage or save data to your server for users in a database temporarily and get it back with an API call(localstorage has a 10MB) limit.
You can have your code try to retrieve localstorage values first if they exist.

Ionic - Adding states dynamically

I am developing a mobile application using Ionic framework. I get a JSON file containing the template and it's controller. The server will push data once there's data in JSON format. The problem is adding the states dynamically, and I have read that it's only possible at the config time.
Please tell me if there's a way to do this through a controller which will only be responsible of receiving and setting the new state and that will also receive the JSON and from it create the new state.
The help is highly appreciated!
Edit
I have found ui-router-extras (http://christopherthielen.github.io/ui-router-extras/#/future), but I don't know how to make it work for my application.
Suppose a controller gets the JSON using $http where the JSON looks like:
{
'name':'preview',
'template':'<h1>Hello</h2>'
}
How to add this state in this controller?
There are some simliar Q & A:
AngularJS - UI-router - How to configure dynamic views - this answer
Start Angular.js route-segment or ui-router after all translations are loaded
Angular - Dynamically Choose Starting State
Which shows, that UI-Router is shipped with a great feature:
$urlRouterProvider.deferIntercept(defer)
Disables (or enables) deferring location change interception.
If you wish to customize the behavior of syncing the URL (for example, if you wish to defer a transition but maintain the current URL), call this method at configuration time. Then, at run time, call $urlRouter.listen() after you have configured your own $locationChangeSuccess event handler.
There are some working plunkers here or here,
showing that in .config() phase we will stop url router:
.config(['$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider) {
// States, which we know about from beginning
// could be declared "statically"
$stateProvider
...
// here we say STOP
$urlRouterProvider.deferIntercept();
}
])
Later, in .run() phase, we will 1) configure states via $http 2) enable url routing
.run(['$urlRouter', '$timeout', '$state',
function($urlRouter, $timeout, $state) {
$http
.get("modules.json")
.success(function(data) {
// here we can use some JSON to configure $stateProvider
// in example we can use $timeout to simulate that
$timeout(function(){
// here we turn all on again...
$urlRouter.sync();
$urlRouter.listen();
// there could be some decision, driven by $http load
// we just use some state as default target
$state.go("parent.child");
}, 1000)
...
Check it in action here or there