Changing routes doesn't refresh data, gives ng:areq error - javascript

In my AngularJS app, I have a route that looks like:
.when('/:project/:page', {
templateUrl: '/ui-editor/editor',
controller: 'EditorCtrl'
})
In a view, I have a link that looks like:
Next page
When I click that link in my app, the URL in the browser changes correctly (e.g. /myproject/1 to /myproject/2), but I get an error Error: [ng:areq] Argument 'scope' is required. The line that the error refers to is the console.log statement in:
socket.on('ws:init-data', function(data) {
console.log('on ws:init-data', data);
// Handle incoming data from server
//...
});
If I refresh my browser, the correct data loads as it should for /myproject/2.

use ng-href is better. It can avoid link be clicked before angular parse.
<a ng-href="/{{currentProjectId}}/{{currentPageId + 1}}">Next page</a>
I don't know the exact cause about this error, but I have a suggestion:
use $location to change your url.
you can see on the dev_guide:
When should I use $location?
Any time your application needs to react to a change in the current URL or if you want to change the current URL in the browser.
http://docs.angularjs.org/guide/dev_guide.services.$location

Related

How to show a popup using an ajax-call, a controller and a fragement

I want to implement a popup showing up on everypage under certain conditions and I want to use a controller/jsp-fragment via an ajax(). But I can't make it work. The purpose of the popup is justto display a message, no user input etc.
My controller:
#Controller
public class PopupController extends AbstractController
{
#RequestMapping(value = "/Popup")
public String myPopup() {
//do stuff, add attributes etc.
return '/mypoppath/mypopup';
}
}
The Controller is new class created for this popup. Maybe I already made a mistake here? Do I have to specify the requestmethod or production type?
The ajax call
popup : function() {
console.log("before ajax");
$.ajax({
url: 'https//:myShop/Popup',
success: function(){
Ready.displayModalPopup(Result,'modal');
console.log("success");
},
error:function(){
console.log("ajaxerror");
}
});
}
Ready.displayModalPopup(Result,'modal'); is a function used in the project to show modal-windows and should work fine, the rest ist written by me.
the popup-function is in Ready.js and is called in initialize()
$(document).ready(function() {
Ready.initialize();
$('[data-toggle="popover"]').popover();
});
The fragment itself has the follwing structure
{
"success" : ${success}
,
<c:if test="${not empty errorMsg}">
"message" : "<spring:theme code="${errorMsg}" />"
,
</c:if>
"myPopup": "<spring:escapeBody javaScriptEscape="true">
<c:url value="/Popup" var="popupUrl"/>
<div id ="myPopup">
--- header---
--- body ---
--- footer---
I used an already working jsp from an already working popup as a blueprint, so I don't think the error lies here.
Right now the behavior is the following:
If load the homepage, no popup shows up, but I can see 2(?) xhrs in the firefoxdebugger, both called "popup" one status :302 and one status 404, so I guess there is already an error within the URL, but I already tried diffrent approaches without succes (If I remember right I had a 200 once, but still no popup). Also the ajaxcall seems to throw an error all the time.
I know there are some similar topics and I tried to solve it with them, but
to be honest I am not a frontendprogrammer and also still learning backend and I coming close to despair with this topic.
It's probably some basicmistakes I do, but I can't find them.
EDIT: When I debug the controller gets called, so I think the URL is working, but there is still an error at the ajax ant the redirect to 404.
Meanwhile I added #ResponseBody. This led to to a popup, but showing only the path of the JSP, not the content.

Get Information from one page to another with angular routing

Image a page, that page is called "dashboard". In the dashboard, there is a drop-down menu, with items, which are listed by the PHP script, and their count varies on the number of results from a database.
Now, when a user clicks one of the items from the menu, it should redirect him to the configuration page, with some data (id, type). Sounds simple, but the redirecting method used is made with angular, so it uses URL hashing, without refreshing the site. URL of configuration page then looks like:
https://www.example.com/index.php#/configure
...and I want to get there some data. The site we see there is just a blank site, which, in the file tree, is named "configuration.php", but you don't see it in the URL, because of angular code in "configure.module.js.php", which simply redirects the user, gives them the right site with:
(function () {
'use strict';
angular.module('BlurAdmin.pages.configure', [])
.config(routeConfig);
/** #ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('configure', {
url: '/configure',
title: 'Configuration',
templateUrl: 'app/pages/configure/configure.php',
controller: 'addCtrl',
});
}
})();
So I assume, that if I want to get the data to my site, I need some kind of a GET request. I figured out, that it will work if I use the GET request like so:
https://www.example.com/index.php?something=works&omg=itWorks#/configure
So my index.php will work with the GET data and write them to a SESSION, which can then be used in configuration.php!
Well, it works, kinda... But the main thing is, that it is all angular, so NO SITE REFRESH AT ALL! That means none of my files will be refreshed, so after I click the button again, the site will not get the GET request again, it will simply redirect me to configuration.php, without dealing with the new data... It will keep the first GET parameters and SESSION.
So there goes my question. how to make it? I really need that one click to send that data to configuration.php, without refreshing the site, but, working and updating.
In html you add ui-sref to like this
ui-sref="configure/({id: valueid})
in file config
url:'/configure/:id'
in your controller add $stateParams like this
function addCtrl($scope,$http,$stateParams)
and use ajax to GET
var params = $.param({'id':$stateParams.id})
$http({
method:'GET',
url:'yoururl?id=' + $stateParams.id,
data:params,
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(onSuccess);

ui-router url parameter with hashtag

I'm working on the routing of my angular application, but I can't seem to find the following:
example.com/#parameter
In this url the #parameter should stay #parameter and get the param data. Now it removes the # and goes to example.com/parameter
If I go to example.com/#parameter it should do the same as it would if I go to example.com/parameter
I have the following in my app.js
url: "/:bandName"
and send this data to my controller with $stateParams
Is there any way to keep the hashtag in the url ?
-- edit
so here is some code that works on enter with /#parameter
$urlRouterProvider.when(':#bandName', '/:bandName')
.otherwise('/');
$stateProvider.state('appband', {
url: "/:bandName",
templateUrl: "main.php",
controller: 'mainController'
})
$locationProvider.html5Mode(true);
With this if I go to example.com/#randomBandName I get redirected to example.com/randomBandNameand I get randomBandName as parameter in my controller
So what I need is on enter that example.com/#randomBandName stays example.com/#randomBandName and that I still get randomBandName in my controller.
But when I remove $urlRouterProvider.when(':#bandName', '/:bandName') I just get an empty page.
There are a few things that look suspect with this:
trailing slash
Are you using HTML5 mode for your URLs? I'd suggest using this URL setup url: "/parameter" if you indeed see param as more of a resource.
You might also read this - https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-make-a-trailing-slash-optional-for-all-routes
query param
If you are intending param to be a query parameter then you need this..
url: "/?parameter"
more on that here - https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters

How to make a failed routing resolve promise load a different template URL?

Learning Angular and running into an issue I cant seem to find a "good" answer to. I've been following the official Tutorial and have a similar setup with a project Im working on.
The $routeProvider .when case for phone details GETS a specific .JSON file based on the name of the phone clicked on in the phone list page. The problem is, if you type in a phone name that doesn't have a .JSON file associated with it, the route still proceeds and shows a blank page. I'm trying to figure out how to prevent this.
I've gotten as far as to add a resolve to .when route. However, I can only prevent the view from changing or use a $location.path redirect. Neither of these seem ideal.
How do I go about showing a "404 page" view for phone that doesn't have a JSON file? In my head, I would show a different templateUrl if the GET request responds with a 404, but cant seem to get it working.
Any help would be great!
Here is the code I've got so far:
My route handling.
.when('/game/:Game', {
templateUrl: 'views/game-detail.html',
controller: 'GameDetailCtrl',
resolve: {
myData: ["Games", "$location", "$q", "$timeout",'$rootScope', function(Games, $location, $q, $timeout,$rootScope) {
var def = $q.defer();
var path = $location.path().toString().substring(6);
// Games service
Games.get({gameName: path}, function(game, s) {
}).$promise.then(
function(data) {
// found game data
def.resolve(data);
},
function(error) {
// couldn't find JSON file
def.reject(error);
}
);
return def.promise;
}]
}
}).when('/pageNotFound', {
templateUrl: 'views/error.html'
})
Root Scope route change error listener:
$rootScope.$on("$routeChangeError",
function(event, current, previous, rejection) {
console.log("failed to change routes");
//$location.path('/pageNotFound');
});
Well, you really don't do it that way, what you would do in this case would be to have your template HTML contain the template for both the success and failure scenario and an ng-switch inside to flip states when the call fails or succeeds.
Also, I think it would work if you tried to copy the idea from directives as well:
Angular.js directive dynamic templateURL
You can try to change the path with the following code:
function(error) {
// couldn't find JSON file
$location.path('/pageNotFound');
}

Prevent route interpretation when adding parameters to URL

In my AngularJS application I have the following routing mechanism:
$routeProvider.when('/questions',
route.resolve('questions',
'questions/',
'questions',
'overview',
access.authorizedAccess))
This works correctly, hitting a URL like domain.com/app/#/questions loading the correct controller and template.
What I want to do is have the option to add parameters to the current URL without triggering a page reload (basically reinterpreting the URL). The problem that I have now is that by doing window.location.hash = '#/questions?query=test'; the route is reinterpreted causing a page reload.
What I have tried to do was this:
$rootScope.$on("$locationChangeStart", function (event, next, current) {
if (next.indexOf('?') > -1)
event.preventDefault();
});
This indeed does not trigger a route reinterpretation, but it removes the parameter from my hash, turning it back into '/questions'.
Can your try the option reloadOnSearch:false during intitializing the routes in $routeProvider. See the documentation here

Categories