Removing # from angularjs and making url pretty - javascript

I want to remove the # from the url
I have used the locationProvider and had in the index.html
Locationprovider is given as
scotchApp.config(function($routeProvider, $locationProvider) {
..
$locationProvider.html5Mode(true);
Here is my script.js
// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);
// configure our routes
scotchApp.config(function($routeProvider, $locationProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'pages/home.html',
controller : 'mainController'
})
// route for the about page
.when('/about', {
templateUrl : 'pages/about.html',
controller : 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl : 'pages/contact.html',
controller : 'contactController'
});
$locationProvider.html5Mode(true);
});
// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
scotchApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
scotchApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
This is the follow up of this question. I still didn't get the solution. I would accept both answer if it was answered.
Here is the plunkr of the example which i wanted to do.
Note :
This is my project folder
localhost/test/angular
So, i have this link in the about
localhost/test/angular/about
Request : Pls download the source from plunkr and have a try over it.
I am not getting any error but nothing appears in the body sections
Thanks

To link around your application using relative links, you will need to set this html code in the head of your document.
<base href="/your-base-if-needed">
or
<base href="/">
but the HTML5 mode set to true should automatically resolve relative links

Related

ng-route doesn't work with other modules

I have the following code
var balaitus = angular.module("balaitus", ["ngRoute"]);
// configure our routes
balaitus.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl : 'home_usuario2.html',
controller : 'usuarioCtrl'
})
.when('/home_usuario', {
templateUrl : 'home_usuario2.html',
controller : 'usuarioCtrl'
})
// route for the about page
.when('/estadisticas', {
templateUrl : 'estadisticas.html',
controller : 'estadisticasCtrl'
})
// route for the contact page
.when('/hashtags', {
templateUrl : 'hashtags.html',
controller : 'hashtagsCtrl'
})
.otherwise({
templateUrl : 'home_usuario2.html',
controller : 'usuarioCtrl'
});
});
// create the controller and inject Angular's $scope
balaitus.controller('usuarioCtrl', function($scope) {
// create a message to display in our view
$scope.message = 'Hi! This is the home page.';
});
balaitus.controller('estadisticasCtrl', function($scope) {
$scope.message = 'Hi! This is the estadisticas page.';
});
balaitus.controller('hashtagsCtrl', function($scope) {
$scope.message = 'Would you like to contact us?';
});
The code simply routes different pages, and set the corresponding controller. It works fine, but when I add another angular module between [ ], for example ngFileUpload or ui.bootstrap.demo, ng-route doesn't work, ¿but why?
you should add it in the constructor, like:
var balaitus=angular.module("balaitus", ['webix', 'ngRoute','ui.router']);
balaitus.config(['$stateProvider', '$urlRouterProvider', '$routeProvider', '$locationProvider', '$qProvider', function ($stateProvider, $urlRouterProvider, $routeProvider, $locationProvider, $qProvider) {
$routeProvider ....
and of course include the js files in ur html code
<script src="Scripts/angular-route.js"></script>

wants to redirect to home page in angular js if user type wrong path and show correct URL

If we edit the URL forcefully the web page shows the same content with different URL.
For example http://www.example.com/# and http://www.example.com/#/abc serves same content.
Wants to Redirect edited URL on Home page every time show correct path in URL.
.state('system.confirmation', {
url: '/confirmation',
templateUrl: 'tpls/views/system/confirmation/confirmation.html',
controller: 'ConfirmationController',
controllerAs:'confirmationController',
}
What you're looking for is the otherswise() function. Try adding this in your config function:
$urlRouterProvider.otherwise('/')
This will make sure that all uncaught routes will be redirected to your base URL.
$rootScope.$on('$routeChangeStart', function (event, next, last) {
console.log(event, next, last)// get all info, about current controller
$scope.someFunction();
});
You can do everything with this, before change any routes, this function will call, there you can check for something you are talking about.
try this
App.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/index', {
templateUrl : 'views/site/index.html',
controller : 'indexController'
})
// route for the about page
.when('/about', {
templateUrl : 'views/site/about.html',
controller : 'aboutController'
})
.when('/404', {
templateUrl : 'views/site/404.html',
controller : '404Controller'
})
.when('/signup', {
templateUrl : 'views/site/signup.html',
controller : 'signupController'
})
.when('/forgotPass', {
templateUrl : 'views/site/forgotPassword.html',
controller : 'forgotPassController'
})
.when('/login', {
templateUrl : 'views/site/login.html',
controller : 'loginController'
}).otherwise({
redirectTo: '/404'
});;
});
App.controller('404Controller',['$scope', function($scope) {
$scope.message = 'Page not found 404.';
}]);

refactor angular-route to angular-ui-router

I've created a single page application using ngRoute like so:
index.html (ngRoute)
var smallTalkzModel = angular.module('smallTalkzModel', ['ngRoute']);
smallTalkzModel.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'components/login/loginView.html',
controller : 'loginController'
})
.when('/chat', {
templateUrl : 'components/chat/chatView.html',
controller : 'chatController'
});
}).run(function ($rootScope) {
// App is loading, so set isAppLoading to true and start a timer
console.log($rootScope);
$rootScope.isAppLoading = true;
});;
small-talkz.model.js (ngRoute)
<div ng-app="smallTalkzModel" >
<div ng-view>
</div>
</div>
Then I heard that it is better to use ui.router because it is a 3rd party which have more capabilities and can does everything that ngRoute does and more and will be supported in future version of angular js...
So, I tried to refactore my code into the code below. which does not work...
Can anyone tell me why? I did not use ng-surf because I don't have any links into my html. I get to them by localhost:3000/somePage and not by navigation...
index.html (ui.router)
<div ng-app="smallTalkzModel" class="loader">
<div ui-view>
</div>
</div>
small-talkz.model.js (ui.router)
var smallTalkzModel = angular.module('smallTalkzModel', ['ui.router']);
smallTalkzModel.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/',
templateUrl : 'components/login/loginView.html',
controller : 'loginController'
})
.state('chat', {
url: '/chat',
templateUrl : 'components/chat/chatView.html',
controller : 'chatController'
});
});;
Expecting that you have included the library ui-router.js in your project. Code looks fine. One thing i think might me causing issue is to define the route when none of the states defined by you matches the state of application. Use otherwise option for that as below:
$urlRouterProvider.otherwise('/');
Code should look like:
smallTalkzModel.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/',
templateUrl : 'components/login/loginView.html',
controller : 'loginController'
})
.state('chat', {
url: '/chat',
templateUrl : 'components/chat/chatView.html',
controller : 'chatController'
})
$urlRouterProvider.otherwise('/');
});
angular-ui-router is based on states.
If you want to go from one state to another then you have to use "ui-sref" or "$state.go()"
for example to go to your chat page (State), use:
<a ui-sref="chat">to go chat page</a>

Routing is not working in AngularJS app

I am making an angularjs app but my routing part is not working.
Once I login into application using Login.html,it should route to index.html but it is not working.
app.js
/**
* Created by gupta_000 on 7/19/2016.
*/
'use strict';
var myApp = angular.module('myApp',[
'Controllers','ngRoute'
]);
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'index.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}]);
I uploaded all my custom files at below location.
http://plnkr.co/edit/mi2JS4y2FfMD9kIl58qk?p=catalogue
I have already included all the dependency files like angular.js and angular-route.js etc..
Thanks in advance.
Here is a working plunker based on your code. You are missing the ng-view that the ngRoute will replace based on your config. So, the index.html looks like:
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<ng-view></ng-view>
</body>
ng-view is an Angular directive that will include the template of the current route (/main or /home/student) in the main layout file. In plain words, it takes the file based on the route and injects it into the main layout (index.html).
In the config, ng-view will be replace by 'main' that points to Login.html. I change the '/home/student/' to point to a new page 'dic.html' to avoid infinite loop as it used to point to index.html
var app = angular.module('plunker', ['ngRoute', 'Controllers']);
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/main', {
templateUrl: 'Login.html',
controller: 'LoginCtrl'
}).
when('/home/student', {
templateUrl: 'dic.html',
controller: 'DictionaryController'
}).
otherwise({
redirectTo: '/main'
});
}
]);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
Like your example, if one logs in with 'harish' as an e-mail and 'harish' as a password, the successCallback is called and goes to '/home/student' that replaces ng-view by dic.html:
$scope.validate = function() {
$http.get('credentials.json').then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Data: ' + JSON.stringify(response));
$scope.users = response.data;
var count = 0;
for (var i = 0, len = $scope.users.length; i < len; i++) {
if ($scope.username === $scope.users[i].username && $scope.password === $scope.users[i].password) {
alert("login successful");
count = count + 1;
if ($scope.users[i].role === "student") {
$location.path('/home/student');
break;
}
}
}
if (count != 1) {
alert("Please provide valid login credentials");
$location.path("/main")
}
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("Error: " + JSON.stringify(response));
alert(JSON.stringify(response));
});
};
Let us know if that helps.
You need to add ng-view in the index.html inside the ng-app.
Something like..
<body ng-app="myApp">
<ng-view></ng-view>
</body>
Now, the angular app would assign the view template and controller as defined by your routes configuration, INSIDE the ng-view directive.
Also, should have a generic index.html where all dependencies are included, and render the templates & assign them controllers in accordance with routes configurations. No need to create separate files which includes the dependencies all over again, like you did with index.html and login.html.
You have not injected $location in your controller.
app.controller('MainCtrl', function($scope, $http, $location) {
$scope.name = 'World';
});

change url without changing state in angularjs

i am using angularjs for developing SPA. i have state loading which there is image with a tag. this is required for a plugin i am using for creating album. but due to this my url is changing and this forces my state to change.
My question is how can i stop changing my state when url changes. or how to stop a tag to change url.
My app config :
var decorpot = angular.module('decorpot', ['ngRoute', 'satellizer']);
decorpot.config(['$routeProvider', '$provide', '$authProvider', function($routeProvider, $provide, $authProvider){
$provide.decorator('ngViewDirective', function($delegate) {
var directive = $delegate[0];
directive.replace = true;
return $delegate;
});
$routeProvider.when('/', {
templateUrl: 'resources/partials/home.html',
controller: 'DecorpotCtrl'
}).when('/projects',{
templateUrl : 'resources/partials/projects.html',
controller : 'ProjectsController'
})
.otherwise({
redirectTo: '/'
});
}]);
image html :

Categories

Resources