Pass parameters by clicking button to other controller - javascript

i got to do a simple CityBike Application for a class at university.
To complete the task, i give the user the possibility to choose between three cities and showing all the free bikes and empty city bike spots at the moment, going forward. Through the service.js I include the api for the citybikes.
I now got two views (start.html & citybikes.html) and i would like to choose one of the three cities in the Dropdown menu and pass it to citybikes.html-controller by clicking on the button.
Is there any simple way to accomplish that?
Here's the main part of the code for the start.html:
<label class="item item-input item-select">
<div class="input-label">
Stadt auswählen
</div>
<select ng-model="choose.name">
<option ng-repeat= "city in citystart"> {{city.CityName}}</option>
</select>
</label>
<p> anzeige? {{choose.name}}</p>
<!--BUTTON-->
<a ng-if="choose.name"
class="button button-block button-positive"
ui-sref="tab.citybike({param1: choose.name})">
CityBikes anzeigen
</a>
And here are the controller:
angular.module('starter.controllers', [])
.controller('Start', function($scope, $stateParams, cities_overview) {
//$scope.citystart = cities_overview.getCities();
})
.controller('CityBikeController', function($scope, $stateParams, CityBikeParis, CityBikeHamburg, CityBikeLondon, cities_overview, chosencities) {
$scope.chosenVar = "";
$scope.chosenVar = $stateParams.param1;
$scope.SumFree=0;
$scope.SumEmpty=0;
var liste = CityBikeHamburg.getList();
switch($scope.chosenVar){
case "Paris":
liste = CityBikeParis.getList();
break;
case "Hamburg":
liste = CityBikeHamburg.getList();
break;
case "London":
liste = CityBikeLondon.getList();
break;
}
liste.then(function(list) {
$scope.stationlist = list.data.network.stations;
for(var i=0; i<$scope.stationlist.length; i++){
$scope.SumFree += $scope.stationlist[i].free_bikes;
$scope.SumEmpty += $scope.stationlist[i].empty_slots;
}
})
})
Finally an excerpt of my app.js that routes the views:
.state('tab.citybike', {
url: '/citybike',
parameter: {
'param1':""
},
views: {
'tab-citybike': {
templateUrl: 'templates/citybike.html',
controller: 'CityBikeController'
}
}
});
I would be very very grateful if anyone could help me out! :)
Greets,
Thomas

You can pass parameter in state param.
Routing :
$stateProvider
.state('tab.citybike', {
url: '/citybike/:param1',
views: {
'tab-citybike': {
templateUrl: 'templates/citybike.html',
controller: 'CityBikeController'
}
},
...
}
Controller :
var param = $stateParams.param1; //get param1 value.
Html :
ui-sref="tab.citybike({param1: choose.name})"

Related

Detail Page View not Showing Data in ionic

I'm new to Ionic. I write code for list. List is working perfectly but when click on any list-item it's not showing any data.
It showing me this error "Cannot GET /pilliondetails/1" how can i solve this?
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
console.log(savedData);
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
})
PillionList Controller:
.controller('PillionListCtrl',function($scope,$ionicHistory,myService){
$scope.myGoBack = function() {
$ionicHistory.goBack();
};
$scope.pillions = [];
var promise=myService.get();
$scope.pillions=myService.get();
})
PillionDetail Controller:
.controller('PillionDetailCtrl',function($scope, $ionicHistory, $stateParams, myService)
{
$scope.myGoBack = function() {
$ionicHistory.goBack();
};
var promise=myService.get($stateParams.requestId);
console.log(promise);
})
PillionList.html :Showing list pf Pillions
<ion-list>
<ion-item data-ng-repeat="pillion in pillions">
<div class="list list-inset">
{{pillion.request_departure_date}}-{{pillion.request_departure_time}}
{{pillion.request_from}} >> {{pillion.request_to}}
{{pillion.user_first_name}} {{pillion.user_last_name}}
<a ui-sref="pilliondetails({pillionId:pillion.request_id})" nav-direction="enter">
<h2>More Details...</h2>
</a>
</div>
</ion-item>
</ion-list>
my app.js
.state('pillionlist', {
url: '/pillionlist',
templateUrl: 'templates/pillionlist.html',
controller: 'PillionListCtrl'
})
.state('pilliondetails', {
url: '/pillionlist/:pillionId',
templateUrl: 'templates/pilliondetails.html',
controller: 'PillionDetailCtrl'
})
Its redirecting to pillionDetail view but not showing data.
Please help.
The first thing i noticed is
ui-sref="pilliondetails({pillion.request_id})"
it should be key-value pair like this
ui-sref="pilliondetails({ your_id : pillion.request_id})"
and in stateProvider, the url of details page should contain parameter. for eg.
url : '/pilliondetails/:your_id'

How do i get the search results of a search page into the next page and display

In this ionic application I want to enter data from the search page and show the results in the next page. But when i try it it wont work. And i can get the search results to the console. and the data wont pass to the next page even i make the same controller for both the pages. Please help me to resolve this issue!! Thanks!!
This is my button code ('searchA' is the object containing entered data)
<button type="button" class="button button-block button-positive" ng-click="search(searchA)" ui-sref="app.MainSearchResult">Search</button>
These are my states (app.js file)
.state('app.MainSearch', {
cache:false,
url: '/MainSearch',
views: {
'menuContent': {
templateUrl: 'templates/MainSearch.html',
controller: 'MainSearchCtrl'
}
}
})
.state('app.MainSearchResult', {
url: '/MainSearchResult,
views: {
'menuContent': {
templateUrl: 'templates/MainSearchResult.html',
controller: 'MainSearchResultCtrl'
}
}
})
This is my search function (controller.js)
$scope.search = function(searchA){
console.log('No : '+ searchA.emp_EPF);
console.log('Name : '+ searchA.emp_Name);
console.log('Company :'+ searchA.emp_Comp);
//console.log('qualification Type : ' + emp_qualiType);
console.log('-------------------');
$http({
method: 'GET',
url: 'http://localhost/mas/Search.php',
params: {employeeNo : searchA.emp_EPF,
employeeName : searchA.emp_Name,
employeeCompany : searchA.emp_Comp,
employeeBusinessUnit : searchA.emp_BU,
employeeTeamName : searchA.emp_Team,
employeeSecondaryCompany : searchA.emp_secondmant,
employeeRelatedEmployee : searchA.emp_relatedEmp,
employeeWorkLevel : searchA.emp_workl,
employeeDesignationName : searchA.emp_designation,
qualificationType : searchA.emp_qualiType,
qualificationField : searchA.emp_qualiField,
programName : searchA.emp_progName,
serviceProvider : searchA.emp_svcProvider
}
}).then(function successCallback(response) {
$scope.searchResults = response.data['records'];
console.log('success :'+ JSON.stringify($scope.searchResults));
}, function errorCallback(response) {
console.log('error',response);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
angular.copy($scope.resetData,searchA);
}
This is my results set view of the next page.
<ion-list ng-repeat="x in searchResults">
<ion-item class="item item-text-wrap" >
<div >
<h2>{{x.employeeNo}}</h2>
<p>{{x.employeeName}}</p>
<div>
<a class="button button-outline button-medium button-positive" >Edit</a>
</div>
</div>
</ion-item>
</ion-list>
Please Help me to get this done!!
Thanks!!
A simple solution is to have a factory return an object and let your controllers on both pages work with a reference to the same object
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
//Make your search request here.
return Data;
});
myApp.controller('MainSearchCtrl', function( $scope, Data ){
$scope.searchResults = Data;
});
myApp.controller('MainSearchResultCtrl', function( $scope, Data ){
$scope.searchResults = Data;
});
The easiest way to share data between views/scopes/controllers, the easiest way is to store it in $rootScope.
In MainSearchCtrl,
$scope.searchResults = response.data['records'];
$rootscope.searchResults = $scope.searchResults;
You can use the same variable on the SearchResults page as well.

AngularJs form not displaying form data pushed to a list

I made a simple AnguarJS app with form and list of books. In list of books I have a form, in which I can type information about book and submit, and my list of book should change. I want to make something like this: http://www.w3schools.com/angular/tryit.asp?filename=try_ng_app4
But when I add information in form, I don't see added infromatioin in book-list, but only empty field. I don't want to send information to the server, I only want to see added information on the web-page. Files, that I use are below:
app.js
var module = angular.module("sampleApp", ['ngRoute']);
module.config(function ($interpolateProvider) {
$interpolateProvider.startSymbol('[[').endSymbol(']]');
})
module.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/route1', {
templateUrl: 'static/myapp/html/test1.html',
controller: 'RouteController1'
}).
when('/route2', {
templateUrl: 'static/myapp/html/test2.html',
controller: 'BookController'
}).
otherwise({
redirectTo: '/'
});
}]);
module.controller('BookController', ['$scope', function($scope) {
$scope.books = [
{
title: 'test',
author: 'test',
}
];
$scope.addMe = function (title, author) {
$scope.books.push({title: title, author: author});
}
}]);
test2.html
<div class="container">
<div ng-controller="BookController" >
<ul>
<li ng-repeat = "book in books">
Title:<p>[[book.title]] </p>
Author: <p>[[book.author]] </p>
</li>
</ul>
<input type="text" placeholder = 'title'/>
<input type="text" placeholder = 'author'/>
<button ng-click="addMe(title,author)">Add</button>
</div>
</div>
After filling form I get the next result:
It does not work because you don't set variable.
You add title and author in addMe but if you console.log these variables, it shows undefined.
You can use $scope. You can see it as the bridge between the controller and the view. So, in your view, when you set the title and the author and click on addMe, you will get it in the controller in $scope.title and scope.author
in the view.
<input type="text" placeholder = 'title' ng-model="title"/>
<input type="text" placeholder = 'author' ng-model="author"/>
<button ng-click="addMe()">Add</button>
In the controller just after the books declaration:
$scope.title = '';
$scope.author = '';
In addMe
$scope.books.push({title: $scope.title, author: $scope.author});
Try setting $scope.books to a new array instead of pushing to it. Angular.js checks which variables have changed by comparing references. Since the variable book stays set to the same array, angular's dirty checking feature might not detect a new element.
Change it to something like this
$scope.books = $scope.books.concat([{title: title, author: author}]);
This should work because concat returns a new array instead of updating the old one.

Get unique item from scope array

I have an array with JSON objects in my $scope.users which is working correctly. I'm now trying to set up a "detail" page for an individual user by filtering the users list to get a single user.
I've been close for an excruciating amount of time, and for some reason I can't find documentation or any examples of how to do what I'm doing. Maybe this isn't the correct way to do this in Angular and/or maybe I'm not searching for the right thing?
I've tried getting the object based on userId from the list in the controller, and I've tried passing a resolve in the state, but I didn't get either method to work. What is the best way to go about getting the single user with id of $stateparams.userId?
Everything else is working correctly (i.e. all the routing, getting the users on #/users).
// routing section of app.js
// Routing
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'static/partials/main/home.html'
})
.state('users', {
url: '/users',
templateUrl: 'static/partials/accounts/users.html',
controller: 'UserController'
})
.state('profile', {
url: '/users/{userId}',
templateUrl: 'static/partials/accounts/profile.html',
controller: 'UserController'
});
// controller.js
var rlGlobalControllers = angular.module('rlGlobalApp.controllers', []);
rlGlobalControllers.controller('UserController', function($scope, $stateParams, $filter) {
var userId = $stateParams.userId;
$scope.users = [
{
'id': 1,
'name': 'Shadrack'
},
{
'id': 2,
'name': 'JP'
},
{
'id': 3,
'name': 'Adam'
}
];
// $scope.user = ???
});
# profile.html
<div ng-include src="'/static/partials/shared/header.html'"></div>
<div class="container">
<div class="row">
<p>users data: {{ users }}</p>
<p>user data: {{ user }}</p>
</div>
</div>
User Array.prototype.filter method to find objects satisfying criteria:
$scope.user = $scope.users.filter(function(user) {
return user.id === userId;
})[0];
This is the most natural way to solve it. If however your users array is very large (like millions, for example (hope it's not)) then for-loop-break solution of juunas is preffered as more effective.
You could just do this in the controller:
for(var i = 0; i < $scope.users.length; i++){
if($scope.users[i].id === userId){
$scope.user = $scope.users[i];
break;
}
}
var output = [],
keys = [];
Array_Value.forEach(function (item) {
var key = item["Field name"];
if (keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
this.Title = output;
Instead of Array_value and field name, give your data.

move to different pages based on the checked radio button

i have this form and it has 3 ionic radio buttons used.Is there a way to a move to different pages according to the radio buttons that are selected.For ex: my radio buttons are named
1.USO
2.OASO
3.TFTSO
I want to move to a different page if i select USO , and to another different page if i choose OASO and so on. I want to move only after i click the 'Proceed' Button that i've implemented in my code.
This is how i've implemented by radio buttons and proceed button in html
<label class="labelColor">
<h5><b>Select Standing Order Type</b></h5>
</label>
<div class="list">
<ion-radio ng-repeat="item in clientSideList"
ng-value="item.value"
ng-model="data.clientSide">
{{ item.text }}
</ion-radio>
</div>
<!-- BUTTONS -->
<div class="col"
style="text-align: center">
<button align="left"
class="button button-block button-reset"
style="display:
inline-block;width:100px;text-align:center "
type="reset"
ng-click="submitted = false; reset()"
padding-top="true">
Reset
</button>
<button class="button button-block button-positive"
style="display: inline-block;width:100px "
ng-click="submitted=true; "padding-top="true">
Proceed
</button>
</div>
my angularjs
.controller('OrderCtrl', function($scope,$state) {
$scope.clientSideList = [
{ text: "Utility Standing Order", value: "uso" },
{ text: "Own Account Standing Order", value: "oaso" },
{ text: "Third Party Fund Transfer Standing Order", value: "tpftso" }
];
$scope.data = {
clientSide: 'uso'
};
})
My controller
.controller('OrderCtrl', function($scope,$state, $http, $ionicPopup) {
$scope.clientSideList = [
{ text: "Utility Standing Order", value: "uso" },
{ text: "Own Account Standing Order", value: "oaso" },
{ text: "Third Party Fund Transfer Standing Order", value: "tpftso" }
];
$scope.data = {
clientSide: 'uso'
};
$scope.move = function () {
var path;
switch($scope.data.clientSide) {
case 'uso': path = '/so/utilitystanding'; break;
case 'oaso': path = '/so/ownstandingorder'; break;
case 'tpftso': path = '/so/thirdstandingorder'; break;
}
$state.go(app.standing);
};
})
.controller('utilityStandingCtrl', function($scope,$state) {
});
Try to add ng-click to your Proceed button and define function which will analyse value of your selected data.clientSide and then call $location.path(url). You need to inject $location service into your controller.
JavaScript:
$scope.goSomewhere = function () {
var path;
switch($scope.data.clientSide) {
case 'uso': path = '/uso'; break;
case 'oaso': path = '/oaso'; break;
case 'tpftso': path = '/tpftso'; break;
}
$location.path(path);
};
And HTML:
<button ng-click="goSomewhere()">Proceed</button>
Demo: http://plnkr.co/edit/jawx0OivVmu2EyNmAbR9?p=preview
Edit
My answer above is related to angular-route, not to ui-router. In the last you need to use all the same code except of function call. Instead of location.path() it must me
$state.go(yourStateName)
Please note, not url, but state name.
Edit2
Here is code for ionic framework (almost the same) + settings of application.
Config:
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('main', {
url: "/main",
templateUrl: 'main.html'
})
.state('usoStateName', {
url: '/uso',
templateUrl: 'page.html',
controller: 'usoCtrl'
})
.state('oasoStateName', {
url: '/oaso',
templateUrl: 'page.html',
controller: 'oasoCtrl'
})
.state('tpftsoStateName', {
url: '/tpftso',
templateUrl: 'page.html',
controller: 'tpftsoCtrl'
});
$urlRouterProvider.otherwise('/main');
});
And function:
$scope.goSomewhere = function () {
var path;
switch($scope.data.clientSide) {
case 'uso': path = 'usoStateName'; break;
case 'oaso': path = 'oasoStateName'; break;
case 'tpftso': path = 'tpftsoStateName'; break;
}
$state.go(path);
};
Demo: http://plnkr.co/edit/0sk3dECPNm35HgMqiprt?p=preview
Instead of {{ item.text }}
Try something like this:
a href=""#/viewName/{{item.text }}"}">{{ item.text }}

Categories