How to add route dynamically in angular - angularjs

I'm writing an EShop project, and i show some products in it which customers can buy them, when the customer click on buy button, i checked whether customer was logged in or not, if not i should route the customer to specific controller for log in process, if customer was logged in i route him or her to another controller, how can i do it?
<script>
app.controller('buyTheItem',function($scope,$http){
//when customer click on buy button then:
$scope.buy = function(){
// here i check whether customer was logged in or not
if(was logged in){
// i should route to buyProductController
}
else{
// i should route to accountController for log in
}
};
});
</script>
before i use window.location but its not right way because i need angular routing, and it's not use this,, any one can tell how can i do it?

For this, I can suggest to you to use UiRouter: https://github.com/angular-ui/ui-router
When you implement uiRouter you can afterwards use service $state
and your code can look like:
if (was logged in) {
$state.go('my state for buyProductController');
} else {
$state.go('my state for accountController');
}
uiRouter has a lot of other advantages, all you can see here: https://github.com/angular-ui/ui-router/wiki

Related

Browser back button going to application page after logout

I have logout button in my angularjs(1.5) application. On click of it calling the login page url.After logout, when i click the browser back button again it is going to my application page instead of login page.
$scope.logOutUser = function () {
$window.location.href = "logoutURL";
}
Can anyone suggest how to implement this in angularjs?
Use $location service's .replace() method
$scope.logOutUser = function () {
$window.location.href = "logoutURL";
$location.replace()
}
Please take this my old post abut the back button issue : How to detect if a user clicks browser back button in Angularjs
You may may need that logic like
$scope.$on('$routeChangeStart', function (scope, next, current) {
if (next.$$route.controller != "Your dashboard Controller Name") {// please be mine dash board controller is your home page after login
// Show here for your model, and do what you need**
$window.location.href = "logoutURL";
}
});
But if you did logout in dashboard page then it would be an issue. At this time you need to maintain a flag with ng-Storage for the user is currently authenticate or not.

Can I reload app without refreshing view?

I am using UI Router in my application, and I am wondering if I can reload - or destroy services when user is logging out, without refreshing the view? So far, when user is logging out, backend logs him out, and he is redirected to the login view. However, all of the services are still working. Any ideas?
Thanks
//Controller where the logout button is called
.controller("ctrl", function(destroyService){
this.logout = function(){
//Probably an ajax request to logout from server.
$http.post("logoutUrl", userId)
.then(function(){
destroyService.destroyAll();
$state.go("loginPage");
});
};
})
.service("destroyService", ["service1", "service2", function(service1, service2){
this.destroyAll = function(){
service1.destroyAll();
service2.destroyAll();
};
}]);
UI Router provides with state transition events, so you can listen for the transition event, and when the transition happens to the login page, you can manually refresh your services. By refresh I mean you can bring them to initial state by initializing them to initial state.
You can keep a function like close() in your service which declares everything again. So you can call this function on logout to refresh your service.
refer this for example: Refresh factory/service instance

Passing variables between views

I am building an AngularJS app.
I will have a users view which will have a few tabs:
User Listing
Account
Contact
etc
Basically, everything under "User Listing' should be disabled until a user is selected on the user listing tab. Those tabs will then become active and will have all the details related to the selected user.
I need to pass the id of the selected user into the other tabs so that I can load the model for those users. Do I add the value onto the $scope?
For testing, I tried $scope.id = 4 in my controller for the listing tab.
Then in my view for my account tab, I tried {{ $scope.id }} but nothing was printed on the screen.
You can use to validate a variable to provide user access to routes.
$routeProvider
.when('/somepage' , {
templateUrl: "templates/template.html",
resolve: {
"check": function($location){
if('Your Condition'){
//Do something
} else {
$location.path('/'); //redirect user to home.
alert("You don't have access here");
}
}
}
})
You can use service to validate the login. And for show hide menus you can use same reference and use ng-hide or ng-show

How to change the URL without reloading the page when back button is clicked in angularjs?

I am using angularjs for my app. It contains a newsfeed. If user needs to view the particular news, he has to click on that particular news and it will redirect to that news. And after viewing the particular news, if user wants to go back to news feed(previous page), he has to click on the browser back button. So, in this case, if user clicks on the browser back button, the newsfeed page is reloading again. But, I dont want like this. I want to disable the reload and take the user to the place where he was before. I browsed a lot on this issue, but there was no absolute solution given. Please, help me out.
When you go back, previous route will be triggered and data will be reloaded. If you want to prevent reloading, place a service in between and cache the data.
$routeProvider.
when('/loadFeeds',{
controller:'LoadFeedCtrl',
templateUrl:'pages/feeds.html',
resolve:{
initData : function(FeedService){
return $q.all(
{
data: FeedService.load()
}
);
}
}
})
And in your FeedService, instead of making http call try to see the data is already available
.service('FeedService',function($q,$timeoute){
this.feeds=[];
this.load = function(){
var deferred = $q.defer();
$timeout(function(){
if(feeds.length===0){
this.feeds.push({title:'First','id':1})
this.feeds.push({title:'Second','id':2})
this.feeds.push({title:'Third','id':3})
this.feeds.push({title:'Fourth','id':4})
}
deferred.resolve(this.feeds);
},2000);
return deferred.promise;
};
})
The timeout service could be replaced with $http or $resource. I used the timeout to simulate the delay
you can take an anchor link and on click event of anchor call this
javascript function
window.window.history.back();
here is the html code for it
<input type="button" id="alnkBack" onclick="window.window.history.back();" value="Back" class="button" />

Angular redirect to home on refresh

What's the best way to direct a user to the home page if they happen to refresh from any other route (or state if you're using ui-router, as I am).
For example - I want them to begin on the inventory page. If they want to make edits, they travel to the edits page, but if they refresh that page, they go straight to the inventory route again.
I havn't used the ui-router but in ng-route we can do it like this
create a controller on top of your ng-view div
<body ng-controller="topController">
<div ng-view></div>
</body>
Define your routes normally but in topController just write this line
$location.path("/")
assuming that "/" is your main page where you want to redirect after refresh, don't forget to define $location
window.onbeforeunload = function()
{
window.setTimeout(function () { window.location = 'homeURL'; }, 0);
window.onbeforeunload = null;
}
Assume that #/inventory is your route, use otherwise
$urlRouterProvider.otherwise("/inventory");
See URL Routing - $urlRouterProvider

Resources