ui-router removes front slash when user uses 'go to forward' button - html

I'm using ui-router (v0.2.11) with html5 mode
Have the following states:
stateHelperProvider.setNestedState({
name: 'stages',
'abstract': true,
url: '/:bakery/:city',
templateUrl: '/app/stages/stages.html',
controller: 'stagesCtrl',
children: stageStates
});
var stageStates = [{
name: 'chooseCake',
url: '/velg-kake',
templateUrl: '/app/stages/choose-cake/choose-cake.html'
};
$urlRouterProvider.otherwise('/oops');
Bakery and City are optional parameters.
For example I'm on home page:
mysite.com/home
If I go to link something like this:
mysite.com/bakery//velg-kake
go back (to home) and go forward it's ok,
but when I use
mysite.com//city/velg-kake
go back (to home) and go forward I get
mysite.com/oops.
I have tried to see the $location path in 'otherwise' function handler and I have gotten
/city/velg-kake
instead of
//city/velg-kake
So seems ui-roter removes first slash.

Related

Prevent adding slash before hash in Angular 7

I want to add the hash in the URL to go to particular section. My code is to reach the customer section in that page
Customers
When I click this link, the URL will be updated like below.
http://www.example.com#customer
But Angular 7 adds slash / before hash # in the URL after some fraction of seconds and URL will become like this.
http://www.example.com/#customer
But the page remains same even though its updating slash.
The issue is When I try to click the Cutomers link again, the URL will be
http://www.example.com#customer
So URL mismatch will happen here as no slash will be there before hash when I click second time. so it reloads the page
How to prevent adding slash before hash in angular 7
By default the anchor scrolling is not enabled in Angular Router (after v.6.1.0).
You can enable it by importing RouterModule like this:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled'
})
Doc: https://angular.io/api/router/ExtraOptions#anchorScrolling
Your anchor will be the id of the div.
Usage
HTML:
<a [routerLink]="['somepath']" fragment="customer">Jump to 'customer' anchor </a>
TS:
this.route.fragment.subscribe(f => {
console.log("f ", f);
const element = document.querySelector("#" + f)
if (element) element.scrollIntoView()
});
Other solutions.
You can use dynamic scrolling.
<div #customer>Customers</div>
<button (click)="scrollToElement(customer)">Scroll</button>.
And in your ts file:
scrollToElement(el) {
el.scrollIntoView();
}
Or
use ViewChild:
#ViewChild("customer") customerElement: ElementRef;
this.customerElement.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
Or use some angular librarie like:
https://www.npmjs.com/package/#nicky-lenaers/ngx-scroll-to

angularjs routing without links

I have two problems.
First my test.html doesn't "see" the products array from his controller.
I don't know why, I have connected the controller with the html in the routing.config.js.
var myapp = angular.module('myapp', ["ui.router", "ngAnimate"]);
myapp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state("foo", {
url: "/foo",
templateUrl:'start.html'
})
.state("test", {
url: "/test",
templateUrl: 'test.html',
controller:'product-controller',
parent:'foo'
})
$urlRouterProvider.otherwise("/foo");
})
myapp.controller('navCtrl', function($scope, $state){
$scope.navigateTo = function(target){
$state.go(target);
}
});
the second thing I want is that the test.html will be activated without the click on the link.
If the mainpage is loaded, the test.html should be loaded too.
At the end I want to delete the <ul> but the result should be the same.
(the foo and the dropdown).
I have made a PLUNK where you can see the problem.
The only solution I had, is to integrate the test.controller.js in the routing.config.js and the test.html in the start.html.
But i hope to avoid this because it makes the code more confusing.
I also looked at the ui-router docs but it doesn't work for me.
.state("foo.test", {
url: "/test",
templateUrl: 'test.html',
controller:'product-controller',
parent:'foo'
})
I hope someone has an idea... thank you! =)
I would take #charlietfl's advice and read up on nested views. Other than that, you had a few errors in your plunkr:
Forgot to load test-controller.js in index.html
Forgot to inject the product-selection module to myapp (so it can resolve the respective controller)
Forgot to add the ngModel to the select element in test.html for data binding to work as expected
Here's your plunkr updated with the select control populated properly.

ionic - $state.go with params issue1

I just create the ionic project and I'm trying to make the sign in and sign up page and I just implement the HTML and CSS. but the problem is I can't change position between controllers.
The URL of controller is changes but the page is not changed. I was trying to import the correct module but I can't find the method.
Make sure in app.js, your templateURL , url is properly defined.
Most of the time it might be your 'URL' problem.
If you navigated from 'main', your next url should be : /main/success or something like that.
.state('tab.main', {
cache: false, //if you want to disable cache in ionic
url: '/main',
views: {
'tab-cases': {
templateUrl: 'templates/tab-main.html',
controller: 'MainCtrl'
}
}
})

Filter table rows depending on value in searhbox

My application consists of the following:
One indexview which my navbar is placed in together with a searchbox, this has a navcontroller.
Two html pages which is placed in a ngview element with 2 different controllers.
customercontroller and contactscontroller. Theese 2 pages have tables which gets data from a service.
How do i pass the value from the navbarcontroller to the other 2 controllers to filter my table?
The Ng-View is not nested inside the navController scope.
This is my route.
app.config(function ($routeProvider) {
$routeProvider
.when("/Customers", {
templateUrl: "app/customers-list.html",
controller: "customerController"
})
.when("/Contacts", {
templateUrl: "app/contacts-list.html",
controller: "contactController"
})
.when("/Prospects", {
templateUrl: "app/saleprospect-list.html",
controller: "prospectController"
})
.when("/Prospects/add", {
templateUrl: "app/salesprospect-add.html",
controller: "addController"
})
.when("/Prospects/:index", {
templateUrl: "app/salesprospect-add.html",
controller: "editController"
})
.otherwise({
redirectTo: "/Customers"
})
});
You can use angularjs custom events to pass information from one place to another.
As shown in this link:
How do I create a custom event in an AngularJs service
Working with $scope.$emit and $scope.$on
You can pass data with these events which can be used by functions listening for them.
You will find many solutions on how to communicate between controllers. As #ArslanW has pointed out, you can use events. Some answers will ask you to use services.
I believe that, as a best practice, you need to store the search text in the URL as query parameters. This has the benefit that if the user wishes to refresh the screen, the search results will not be reset because you can read the search text from the URL's query parameters.
Check Github.com's issue tracker for example. There you can search for issues and even if you refresh, you search result or text is not lost.
To carry this out, you need two watchers.
One watcher in your NavController to watch the search text and to copy it to the URL.
So, if your search text has the following markup:
<input type="text" data-ng-model="searchText">
... you need to have the following watcher on the input model (in your NavController)
$scope.$watch('searchText', function () {
//This causes the URL to look like
//http://localhost/#!/path?searchText=my%20search%text
//where the search text is "my search text"
$location.search('searchText', $scope.searchText);
});
Now that the URL will get updated, you can use the URL itself to determine which search text to use.
Thus, in the controller for your two HTML views (CustomerController and ContactsController that will display tables, you can then watch the search text for changes:
$scope.$watch(function () {
return $location.search().searchText;
}, function (value) {
//The search text may be undefined - possible when the page
//loads and the user has not entered anything in the search box
if (value) {
//"value" is the search text entered by the user.
//You can then use this and proceed accordingly.
}
});
You have thus hit two bushes with one stone. Your search text is stored in the URL which causes the application to not lose the search text on refresh. You have also communicated with each controller about the search text entered.
Note that since you are adding query parameters to the search text, your page will refresh. To prevent this, add the reloadOnSearch property to your route and set it to false:
$routeProvider
.when("/Customers", {
templateUrl: "app/customers-list.html",
controller: "customerController",
reloadOnSearch: false
});

How to use Dynamic URL's to create Dynamic pages in Angular JS

I have put the question at the bottom as the only way I could explain my problem was with an example so with out the example it might not make sense but feel free to skip down to the bottom and just read the question.
I will use this example to try give some idea of what I do understand and where my understanding falls down.
I want to build a page where I can browse through a collection of items which I would set up like this:
angular.module('App')
.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('browse', {
url: '/browse',
templateUrl: 'app/browse/browse.html',
controller: 'BrowseCtrl',
title: 'Browse',
mainClass: 'browse'
});
}]);
Each item is pulled through and place on this page using ng-repeat and then calling an api:
$scope.items = [];
$http.get('/api/items').success(function(items) {
$scope.items = items;
socket.syncUpdates('Item', $scope.items);
$scope.totalItems = $scope.items.length;
$scope.$watch('currentPage + itemsPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage),
end = begin + $scope.itemsPerPage;
$scope.filteredItems = $scope.items.slice(begin, end);
});
});
This then accesses the api and repeats out the items. So far so good. Heres an example of the API setup. Worth mentioning I am using the Angular-fullstack generator which plugs in to Mongo DB using Express & Sockets.io
Item.find({}).remove(function() {
Item.create({
"image_url" : "../../../assets/images/test.jpg",
"title" : "Test Item",
"created_on" : new Date(2014, 9, 23, 3, 24, 56, 2),
"creator" : {
"profile_img" : "../../../assets/images/stephanie-walters.jpg",
"username" : "StephW",
"url" : "/stephanie-walters",
"first_name" : "Stephanie",
"last_name" : "Walters",
}
}
Ok now this is where things start to get unclear for me.
I now need to create the item pages, so that when I click on an item I get access to the content of that item. Short of creating every single page for every entry I would very much like to be able to create a page template that ui-router is able to attach content to when the correct url structure is met.
Thats probably not clear so let me try be a bit clearer. Lets say if we follow that JSON above I want to go to 'Stephanie Walters' profile I am going to need three things.Firstly a profile template, secondly I need the content for the profile in an api call and lastly a dynamic url that can take that api content and put it in to the page template.
Perhaps something similar to:
.state('profile.username', {
url: '/:username',
templateUrl: '/partials/profile.username.html',
controller: 'profileUsernameCtrl'
})
But I don't exactly understand how to get the take a variable like username from the item JSON(above) and then use that to build a URL /:username that connects to a template page profile.username.html and further still fill that page with the users content that is stored in another API call.
To "build a url" so to speak, you need to use the ui-sref directive.
Given a state like so:
.state('profile.username', {
url: '/:username',
templateUrl: '/partials/profile.username.html',
controller: 'profileUsernameCtrl'
})
to create a link to this state use:
<a ui-sref="profile.username({username: user.name})">{{ user.name }}</a>
where user is an attribute on the scope where that link is displayed.
For more complex URLs you just add additional parameters like so:
.state('browse.item', {
url: '/:username/:itemId'
})
To get the parameters you use the $stateParams service in your controller like so:
.controller('MyController', function($scope, $stateParams) {
$scope.username = $stateParams.username;
$scope.itemId = $stateParams.itemId;
})