angularjs routing based on conditions case statements - angularjs

I have a different requirement for my angularJS views.
I have a cart running where an individual can checkout with 0$ as well ( some free gifts )
So, for the payment page view we came up with a different idea.
if($cart_total>0){
show payment page view;
} else {
show confirmation page view;
}
so how do I do the same in angularJS routing. My angular routing looks like this
as.config(function($routeProvider, $httpProvider) {
$routeProvider
.when('/index', {templateUrl: 'partials/index.html', controller: 'IndexListCtrl'})
.when('/shop/:id', {templateUrl: 'partials/shop.html', controller: 'ShopCtrl'})
.when('/payment/:id', {templateUrl: 'partials/payment.html', controller: 'PaymentCtrl'})
.when('/confirm', {templateUrl: 'partials/confirm.html', controller: 'ConfirmCtrl'})
.otherwise({redirectTo: '/index'});
});
So I need to show payment view only when cart_total > 0 else show confirm view.
Please help !!!

I think you have to use $route service events
PS. Here is similar question

First add a definition to your routes by declaring a constant like that.
angular.module("App")
.constant('Cart', {
showCart : 'true'
});
.when('/payment/:id',{
templateUrl:'',
access:Cart.showCart
})
Then you have to options. First in the run function check '$rootScope.$on('$locationChangeStart' event and inside it you can access the route by var location = $location.path(); var route = $route.routes[location];and then access the user role by route.access; then you can remove or add Html components.Or you can make a simple directives that dose the same route checking and use the link function to remove or add Html component

Related

Providing variables outside of ng-view

So, I have an HTML page, /profile#IDGoesHere which is tied an an ng-app. The ng-app has three columns (with Bootstrap) and the middle of which is utilising Angular's ng-view.
So it's something like this:
/profile#IDGoesHere (and within it):
All Activity
Posts
Likes
Dislikes
etc
The href links are set on the HTML page outside of the ng-view so when I go into the /profile#IDGoesHere page, I set the userID into a variable using a service. Like below:
profileApp.service('globalParams', function() {
var profileID = '';
var user = {};
return {
getProfileID: function() {
return profileID;
},
setProfileID: function(value) {
profileID = value;
}
};
});
I pass the 'globalParams' service into each controller as I need to access the profileID in order to make further calls to get the specific data for the user.
My Angular Router looks like this:
$routeProvider
.when('/profile:id', {
templateUrl : 'partial/profile/feed.html',
controller : 'mainController',
resolve:{
myData: ['$http', function($http){
return $http.get('/session');
}]
}
})
.when('/posts', {templateUrl: 'partial/profile/posts.html', controller: 'postsController'})
.when('/agreed', {templateUrl: 'partial/profile/likes.html', controller: 'likesController'})
.when('/disagreed', {templateUrl: 'partial/profile/dislikes.html', controller: 'dislikesController'})
.when('/comments', {templateUrl: 'partial/profile/comments.html', controller: 'commentsController'});
});
Now the problem, the links to Posts, Likes, Dislikes etc do not have the profileID in them as they are set when you go to the main route, /profile#IDGoesHere.
This works when I am on the page and keep navigating by using the 'globalParams' service however, if I were to refresh the page when I was on one of the sub-pages, the data is lost.
Note: I can't make the whole page to reload which is why I used the ng-view. I could fix this by doing that but it will defeat the purpose of a single page application.
Does anyone have a good idea on this? Been pulling my hair but feel I am missing something very obvious.
Thanks in advance
Edit: as it was causing some confusion, I have added a screenshot to demonstrate how it looks like:
Got it fixed by attaching the whole < body > to a parent controller and under that controller, I used the $window.location.href and split the ID from URL and then added it to the service, which I could then add to the outer hrefs for my sub-pages, essentially making the sub-pages to have a routeParam as well

Simple AngularJS routing not working properly

For some reason, I can't seem to route to the add screen. What am I doing wrong? Here's my app.js
var moviesApp = angular.module('moviesApp', ['ngRoute']);
moviesApp.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/home.html',
controller: 'MoviesController'
})
.when('/add', {
templateUrl: 'partials/add.html',
controller: 'MoviesController'
})
.when('/edit', {
templateUrl: 'partials/edit.html',
controller: 'MoviesController'
});
});
Here's the anchor tag:
Add Movie
Which is contained within my home.html template which is a part of index.html.
The app doesn't crash...it just doesn't do anything.
Any thoughts on what I'm doing wrong?
It may be because of the change in the default hash-prefix in angularjs version 1.6. What you have written works in the given context: Proof
You can confirm this is the case by changing:
Add Movie
to:
Add Movie
If it works look at for possible solutions at:
AngularJS: ngRoute Not Working
If you want to make i behave as you expect (version 1.5) you could choose soultion 3 from the link:
3. Go back to old behaviour from 1.5 - set hash prefix manually
app.config(['$locationProvider', function($locationProvider) {
$locationProvider.hashPrefix('');
}]);
set up a route start event to help debug the problem
.run(function ($rootScope) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
console.log(event);
console.log(current);
console.log(next);
console.log('$routeChangeStart: ' + next.originalPath)
});
});
just add this to the end of your route config
Just as a side note I would use a state provider over a route provider. State providers let you define a hierarchy. It's a little harder to work with but much more flexible.

Angular-js - dynamically create navi

I'm new to Angularjs and have sat through many tutorials to improve my knowledge. All tutorials show me how to use $routeProvider to load templates into view. However they only show me examples that assume the routes are known and I would like to learn how to dynamically create those routes so I can pull a list of unknown nav items from the db and create those routes in a loop.
So, typically a tutorial will show;
$routeProvider.when('/', {
templateUrl : 'views/home.html',
controller : 'mainController'
})
But what if I don't know what those routes will be in advance?
Unfortunately you can't create routes dynamically. You can only configure your routes in the module.config(). I think you search for routes with rest parameters.
Here an quick example with a list view and a detail view that shows one item of the list. Assume the backendService to be defined. The resulting url for the list is .../#/list and for the detail view of an item with the id 12345 the url is .../#/list/12345. Note that all route params are interpreted as strings. So routeParams will be {id: "12345"}.
In the angular phonecat step #9 is a good example of angular router.
angular.module('app').config( function($routeProvider) {
$routeProvider.when('/list',
{
templateUrl: 'views/list.html',
controller:'listCtrl'
}
).when('/list/:id',
{
templateUrl: 'views/detail.html',
controller: 'detailCtrl'
})
});
angular.module('app').controller('detailCtrl',
function($scope, $routeParams, backendService) {
$scope.items = backendService.getItemById($routeParams.id);
}
);

$location.path or $location.url doesn't trigger the ngRoute controller

I have a route defines as follows:
$routeProvider.
when('/projects/', {
controller: 'ProjectCtrl',
controllerAs: 'project_ctrl',
templateUrl: '/static/app/partials/project.html'
}).
After the login finishes I need the user to land on this link, hence in my controller I am using this:
vm.login = function(form) {
if (form.$valid) {
loginService.login(vm.loginFormData.username, vm.loginFormData.password);
loginService.setUpUser()
$location.url("/projects");
}
}
But unfortunately the controller associated with this view is not triggered, that is ProjectCtrl is not triggered. However when I click on the navigation link which uses in the dom, it works fine. Can someone please guide me here, may I am missing something conceptual.
Hence the larger question is how do I redirect a user in the controller using some APIs which also complies with ngRoute based controllers.
Try removing the last / in url so it matches $location.url("/projects");
$routeProvider.
when('/projects', {

Displaying separate data from API in different places on page in Angular

I have a SPA that will display data from an API in two separate parts of the page. One section displays products and prices. This information will remain on the page. The other section is a basic CRUD view. It allows the user to create new selections, read their selections, edit their selections, and remove their selections. I'm trying to determine the best way to display these two views. The CRUD section uses ng-view. Should the price/product section use a directive, a separate controller, or should I break up the page into two modules?
I'm new to Angular, and want to make sure that I do things right to avoid unforeseen issues down the road.
HTML:
<div ng-view="">
<!--user selections go here -->
</div>
<!--Product/Price info will go here. Unsure whether to insert ng-app="new module", ng-controller="new controller", or a directive with its own element-->
Javascript for user selections view:
myApp.config(function ($routeProvider) {
$routeProvider
.when('/list', {
templateUrl: 'views/list.html',
controller: 'ProjectListCtrl as projectList'
})
.when('/edit/:projectId', {
templateUrl: 'views/detail.html',
controller: 'EditProjectCtrl as editProject'
})
.when('/new', {
templateUrl: 'views/detail.html',
controller: 'NewProjectCtrl as editProject'
})
.otherwise({
redirectTo: '/'
});
});
Factory for CRUD / user form section:
myApp.factory('Projects', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL+'/projects')).$asArray();
});
Factory for product list/price section:
myApp.factory('Products', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL + '/products')).$asArray();
});
The native Angular router is limited when creating complex and nested UIs, but AngularUI Router is a great alternative and very widely used. If you want to include multiple views in your interface then this is the way to go. It's not much more complicated than the native router but the wins are huge.
AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. Unlike the $route service in the Angular ngRoute module, which is organized around URL routes, UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.
Here's a Plunker to demo your particular case: http://plnkr.co/edit/xZD47L?p=preview
With ui-router you can name views
<div ui-view="viewName"></div>
and include templates and controllers in the corresponding ui-router configuration
myApp.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, redirect to /
$urlRouterProvider.otherwise("/");
$stateProvider
.state('home',{
url: "/",
// list your views
views: {
"viewName": {
templateUrl: "viewName.html" ,
controller: "viewNameCtrl"
}
}
})
});
Checkout this Wiki for Multiple Named Views.
I hope this helps.

Resources