How do I ignore parts of the URL? - javascript

Currently I have a local server running with my main page at localhost
I ideally want the setup where the url has a key that I send off to my database to get data and the main page loads that data
For example, someone enters the url of localhost/4962 then 4962 gets sent off to the database, while localhost loads. I am using angularJS so I do have a way of getting the url by doing...
var module = angular.module('app', []).run(function($rootScope, $location) {
$rootScope.location = $location;
});
Then location.absUrl() gets me the complete URL.
But obviously there is no page at localhost/4962, so i just get a 404.
How do i ignore the numbers in the url? Also how do I get just the numbers, I would be willing to do localhost/#/4962 if a hash would simplify matters.
EDIT:
Below are some useful answers. Here is what I went with -
var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when('/:message',
{
template: " ",
controller: "AppCtrl"
}).otherwise({redirectTo: '/'});
});
app.controller("AppCtrl", function($scope, $routeParams) {
$scope.model = {
message: $routeParams.message
}
//debugging
console.log($scope.model.message)
});
I needed to have
<ng-view></ng-view>
in the index.html.
Angularjs using $routeProvider without ng-view has a way of avoiding the addition of ng-view. Will try that next.

Do it like this:
angular.module('app', ['ngRoute']).config(function($routeProvider, $locationProvider){
$routeProvider.when('/:number?', {
controller: 'homeCtrl',
templateUrl: '/home.html'
});
$locationProvider.html5Mode(true);
}).run(function(){
...
});
In this case, number is optional route paramerer (because it has ? at the end). Then you can get number from controller:
angular.module('app').controller('homeCtrl', function($routeParams){
var number = $routeParams.number;
});
Don't forget to include angular-route.js file ;)

You can use the $location.path()-Function, should return just the path (without hashtag).

Related

Angular Controller returns 404 on a Route Parameter

I'm building my first web app with Node.js and AngularJs. My problem lies in this code here:
var app = angular.module('Martin', ['ngResource','ngRoute']);
app.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'partials/home.html',
controller: 'PageCtrl'
})
.when('/etx/:id', {
templateUrl: 'partials/page.html',
controller: 'PageCtrl'
});
}]);
app.controller('PageCtrl', ['$scope', '$resource', '$routeParams',
function($scope, $resource, $routeParams){
console.log('Got here');
var Page = $resource('/api/pages/:id');
Page.get({ id: $routeParams.id }, function(page){
$scope.page = page;
});
}]);
From what I understand, if I were to request /etx/mypage, the function in PageCtrl should be run, but when I try to pull it up in a browser, I get a 404 error and nothing is printed to the console.
I tested it with the home page ('/'), and the controller works fine then.
As #Claies identified, the problem was I forgot the octothorpe (or hashtag if you want to be less cool) in the URL. So it should not be etc/mypage, but #/etc/mypage. This behavior is less than ideal in many cases (including mine), so I recommend disabling this with HTML5 mode for links.

Angularjs changing route doesn't load data (ngRepeat)

Of course, I should mention that I'm new to this thing, so sorry if this is something trivial.
So I pretty much have 2 routes (views). localhost:3000 takes in and loads up a list of objects and localhost:3000/:slug shows information of the product the users wants to see more info about.
The initial listing is fine. You visit localhost:3000 and you see a list of items.
listPhoneController.js:
angular.module('cmscApp').controller('listPhoneController', ['$scope', '$http', '$location', 'searchBoxFactory',
function($scope, $http, $location, searchBoxFactory) {
$scope.listInfo = searchBoxFactory;
$scope.phoneList = [];
$http.get('/api/getallphones').then(function(res) {
$scope.phoneList = res.data;
}, function() {
$scope.errorMsg = 'Error in reaching data';
});
}]);
list.html:
<!-- ... --->
<div class="result" ng-repeat="phone in phoneList | hasImageFilter:listInfo.imageRequired
| nameFilter:listInfo.phoneName
| priceFilter:listInfo.price.from:listInfo.price.to">
<!-- filters don't seam to be the problem (removing them still causes the issue) -->
<a ng-href="/phone.slug">More info...</a>
<!-- ... -->
</div>
Now, if I click on the a tag, I get redirected to that phone's information view (ie. localhost:3000/samsung-galaxy-s4) and information is being loaded correctly. I also have a back button there, with a simple <a ng-href='/'>Back</a>
But, when I go back, even though the URL changes back to localhost:3000, the list doesn't appear. I get no errors, nothing, but the div's aren't there (when inspecting, nor anything).
Is this because $http is async, so it tries to load the page before it gets the info? If that's the case, why doesn't it just bind the data, as usual?
Here's my config:
angular.module('cmscApp').config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: '/pages/list.html',
controller: 'listPhoneController',
controllerAs: 'lpc'
})
.when('/:phoneSlug', {
templateUrl: '/pages/detail.html',
controller: 'detailPhoneController',
controllerAs: 'dpc'
})
.otherwise({
templateUrl: '/error/404.html'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
});
Any sort of help is more than welcome!! I thought about storing the data from $http to a factory, so then it loads that data every time the controller is run, while updating it as well. would that be a viable solution, or is there something better?
Turns out the scope didn't bind for some reason, so I had to edit the $http.get().then() method:
$http.get(...).then(function(res) {
$scope.data = res;
$scope.$apply();
}, function() { ... });
for anyone encountering a similar issue

Angular : is an app crawlable with no href but only ng-click function?

I would like to know if my app would be crawlable if I do not use href on my link but only a data-ng-click function. For example, will the page2/index.html will be visit by the google bot if I code it the way below, and if not, what should I put in the href so it is?
The HTML
go page 2
The routes
app.config(function ($routeProvider) {
$routeProvider
.when('/page2',
{
templateUrl: 'views/app/page2/index.html'
})
});
And the GO() function
app.run(function ($rootScope, $location) {
$rootScope.go = function (route) {
$location.path(route);
}
});
Thanks guys
No, it will not be indexed. You should at least create a sitemap.xml.
angular app (and every spa app) is never crawlable because content are injected into DOM by javascript and not by server side processes

Using $routeProvider for dynamic routing and compiling angular code

this has been bugging me for days and i can't figure this out.
i have a website that adds articles at certain points so i figured i shouldn't need to change the routing every time i add a page. so i added this to my project:
$routeProvider.when ('/pages/:page', { templateUrl: 'page.html', controller: 'pageCtrl' });
then i use this for the pageCtrl:
app.controller('pageCtrl', function ($scope, $http, $q, $routeParams, $sce, $location) {
$http.get("partials/" + $routeParams.page + ".html")
.then(function(ret) {
$scope.content = $sce.trustAsHtml(ret.data);
}, function(err) {
$location.path("/404")
});
});
then in the webpage i put a
<div ng-view ng-bind-html="content">{{content}}</div>
and all works well except when i put angular code in there. it seems that it will only parse regular html code but not the ng-stuff. i think i should put a $compile in there somewhere. but i tried all combinations i could think of but none work.
things i tried:
$scope.content = $compile($sce.trustAsHtml(ret.data))($scope);
var e=angular.element($sce.trustAsHtml(ret.data));
c=$compile(e);
$scope.content = c;
c($scope);
and several others that didnt do anything at all..
what's the right way to add content in a view and have angular directive work properly?
This should work well with ng-include within your page.html template:
page.html:
<h1>Page {{name}}</h1>
<div ng-include="contentUrl"></div>
Then your pageCtrl can set these to:
app.controller("pageCtrl", function($scope, $routeParams){
$scope.name = $routeParams.page;
$scope.contentUrl = $routeParams.page + ".html";
})
Here's a working plunker

In AngularJS how can I load scripts when the View changes?

In AngularJS it has the ability to route a section of the page using ng-view. This is really nice for smaller projects but as projects get larger it does not scale very well due to the inability to load scripts in the script tag. I've seen a few other posts that regard this but I cannot get a solution to work. The only way I can get it to work (I consider it a hack and doesn't work the way I would like it) is if I include all the scripts at the top of the base Index.html.
What I would like is when the view changes to have the Javascript files, in the header of the View being loaded, be loaded at that point since they are going to actually be used at that point and not have to pre-load them at the beginning of the application.
http://plnkr.co/edit/7LMv0j2sAcjigPuW7ryv?p=preview
In the demo project the Index.html calls the console.log command but I cannot get page1 or page2 to call the log command. Any help would be greatly appreciated.
I am using Angular 1.3.0 Beta 11.
2 things, in your view you don't have to write <html> or <body> tags, you've already got those on you main page. You should see the view as a part of the main page.
second, to add javascript to your views you add a controller to the view like this:
.config(function ($routeProvider) {
$routeProvider
.when('/page1', {
templateUrl: 'page1.html',
controller: function ($log) {
$log.info('page 1');
}
})
.when('/page2', {
templateUrl: 'page2.html',
controller: function ($log) {
$log.info('page 2');
}
});
});
it's also possible to add a controller to a view like this:
var app = angular.module('routeApp', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/page1', {
templateUrl: 'page1.html',
controller: function ($log) {
$log.info('page 1');
}
})
.when('/page2', {
templateUrl: 'page2.html',
controller: 'ViewController'
});
});
app.controller('ViewController', function ($log) {
$log.info('page 2');
})
i updated your plunker: Here

Categories

Resources