ionic - $state.go with params issue1 - html

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'
}
}
})

Related

Angularjs - Append html code to body when URL changes

I'm working on single page aplication based on Angular. I want to do something like card stack made from divs. Like this.
Idea is that app will have some url links and card should be append when url changes. For example I have 4 links. Home | About | Contacts | Details
On page load will append home card then About etc. So url will change and next card should append.
So my question is: how append some html block when url changes in Angular? I mean that url will be changed but view should be the same and I want just append some html to existing view
Thanks
If using ui.router you can do it like this and update the scopes with the images.
Here is a code example
'use strict';
angular
.module('myApp', [
'ui.router'
])
.config(function ($locationProvider, $stateProvider, $urlRouterProvider, $compileProvider) {
// define states
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/home.html'
})
.state('about', {
url: '/about',
templateUrl: 'views/about.html'
});
// define alternative route
$urlRouterProvider.otherwise('/');
})
.run(function ($rootScope) {
// image changes with route change
if(toState.url === '/') {
$rootScope.headerImg = 'images/headers/home.jpg';
} else if (toState.url === '/about') {
$rootScope.headerImg = 'images/headers/about.jpg';
} else {
$rootScope.headerImg = 'images/headers/error.jpg';
}
});
});

Store HTML page in memory with Angular2

I would like to keep web page in memory so that when I click on back button (not the one on web browser) or on a routerlink, the HTML page instantly loads if I already visit it(because I have some data to load that I don't want to be reload).
I've seen a method with tabbed interface : https://www.w3.org/Style/Examples/007/target.en.html#tab1
but it is not adapted for my code architecture.
I'm using routerlinkin angular2 to navigate threw pages and a back button calling a function on click to go to the previous page.
I try to detail as far as I can so people can understand better my code architecture and the way routerlink method works.
Back button function (works independently from routerlink) :
goBack() {
window.history.back();
}
The router link method from page 1 to page 2:
page1.html :
<a[routerLink]="['PAGE2']"> go to page 2</a>
page1.ts component:
import { Router, ROUTER_DIRECTIVES } from '#angular/router-deprecated';
#Component({
selector: 'page1',
templateUrl: 'page1.html',
styleUrls: ['page1.css'],
directives: [ROUTER_DIRECTIVES]
})
main.ts :
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '#angular/router-deprecated';
#Component({
providers: [ROUTER_PROVIDERS]
})
#RouteConfig([
{ path: '/page2', name: 'PAGE2', component: Page2}]) //component representing class Page2 in page2.ts
Any idea to help me manage it is welcomed, thanks by advance !
Just cache the data in the service like explained in What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?
There is currently no way to prevent the router from re-creating the component when you route away and back to the component.
Well, for those having the same problem, I think the best way to manage it is to map the data into a localStorage key like this :
localStorage.setItem('favoris',JSON.stringify(my_array)); //set my data array
array = JSON.parse(localStorage.getItem('key_name')); //get in array
And then ngOnInitin the class called by the router will call the initial function depending of localStorage key being true or not.

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.

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;
})