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'
Related
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.
I'm able to pass a router parameter when clicking a link to our 'count' page
$state.go('count', {targetName: object.name})
Because of what is established in the router as seen below:
url: '/count/:targetName',
We are using the data: option within UI-Router in combination with $state to dynamically set our page titles
<title ng-bind="'Application Name : ' + $state.current.data.pageTitle"></title>
I would like the pageTitle to include the :targetName. So in order to do that I believe i need to set a function in the data: property of the router. I've tried something like this:
data: {
pageTitle: function () {
getTargetName.$inject('$stateParams');
function getTargetName ($stateParams) {
return $stateParams.targetName;
}
}
}
This doesn't allow the page to resolve at all.
Any tips?
There is a working plunker
Let's have these kinds of states
// this is just a state, with its own pageTitle STRING
.state('home', {
...
data: {
pageTitle: "Just a home page"
},
})
// this is a parent state, with URL parameter 'someParam'
// nad pageTitle as a function
.state('parent', {
...
url: "/parent?someParam",
data: {
pageTitle: function ($stateParams) {
return `title with a param ${$stateParams.someParam}`;
}
}
})
// and to show that child can change it
.state('parent.child', {
...
data: {
pageTitle: "just a child title",
}
})
to make this line of code working:
<title>The tile is: {{ getTitle() }} </title>
we can just add small evaluation into $rootScope, but of course, it should be some service... take it as a simplified how to:
.run(['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.getTitle = function(){
var state = $state.current;
var params = $stateParams;
if (state.data
&& state.data.pageTitle) {
if(typeof (state.data.pageTitle) === "function" ){
return state.data.pageTitle(params);
}
return state.data.pageTitle
}
return "no title for this state"
}
}])
and all these links will have different title
<a href="#/home">
<a ui-sref="parent({someParam: 1})">
<a ui-sref="parent({someParam: 'someValue'})">
<a ui-sref="parent.child">
Check it in action here
I do not know what is wrong, ng-repeat is not
populating the information on my div, please look at the following
and advice where I have gone wrong
app.js
var mainApp = angular.module('mainApp', ["ngRoute", "ngResource"]);
mainApp.factory('EventListFactory',['$resource', EventListFactory]);
mainApp.controller('EventListCtrl', ['$scope','EventListFactory', EventListCtrl]);
var configFunction = function ($routeProvider) {
$routeProvider.
when('/Register', {
templateUrl: 'routesDemo/Register'
})
.when('/UpdateProfile', {
templateUrl: 'routesDemo/UpdateProfile'
})
.when('/Events', {
templateUrl: 'routesDemo/Events',
controller: EventListCtrl,
})
.when('/routeThree', {
templateUrl: 'routesDemo/three'
});
}
configFunction.$inject = ['$routeProvider'];
mainApp.config(configFunction);
EventListFactory.js
var EventListFactory = function ($resource, $location) {
var baseUrl = "";
if (window.location.hostname == 'localhost') {
baseUrl = "http://localhost:52182/api/Events/GetEvents/";
}
else
{
var deployAt = window.location.href.substring(0, window.location.href);
baseUrl = deployAt + "/api/Events/GetEvents";
}
var respone = $resource(baseUrl, null, { query: { method: 'GET', isArray: true, url: baseUrl }, get: { method: 'GET', url: baseUrl } });
console.log("api json at :" + baseUrl);
var records = respone.query();
console.log(records);
return records;
}
EventListController.js
var EventListCtrl = function ($scope, EventListFactory) {
$scope.Message = 'I work';
$scope.items = EventListFactory;
};
EventListCtrl.$inject = ['$scope'];
in the html:
<div id="listView" >
<h1 class="form-signin-heading">For real {{Message}}</h1>
<div ng-controller="EventListCtrl">
<p class="form-signin-heading">Populated Data</p>
<div ng-repeat="item in items ">
<span class="control-label">Heading : </span> {{item.Heading}}
<br/>
<span class="control-label">Event Date : </span> {{item.EventDate}}
<br/>
</div>
</div>
</div>
running the site:
api call from browser:
the code for ng-repeat is correct, but your items is an empty array so nothing gets displayed.
From the screenshots it appears that records in EventListFactory.js does not return an array but a promise.
In EventListController.js instead of
$scope.items = EventListFactory;
Try something like:
var promise = EventListFactory;
promise.then(function(data){
$scope.items = data;
})
I am trying to add to a list in a home.html and display the list in myOrders.html using ionic and angularjs.
The problem is that when I push a new item to the array, the previous items get replaced with the new item.
Example:
push 'one' -> array is [{'name':one'}]
push 'two' -> array is [{'name':'two'},{'name':'two'}] // should be
[{'name':'one'},{'name':'two'}]
push 'three' -> array is [{'name':'three'}, {'name':'three'},
{'name':'three'}] // should be
[{'name':'one'},{'name':'two'},{'name':'three'}]
I have added the relevant parts of my code below.
home.html (Add to list)
<ion-view title="Home">
<ion-content ng-controller="homeCtrl">
<form ng-submit="submitForm(product)" class="list">
<input ng-model="product.name" type="text">
<input type="submit" value="Search" class="button">
</form>
</ion-content>
</ion-view>
myOrders.html (Display list)
<ion-view title="My Orders">
<ion-content ng-controller="myOrdersCtrl">
{{ product }}
</ion-content>
</ion-view>
controllers.js
angular.module('app.controllers', [])
...
.controller('homeCtrl', function($scope, $state, formData) {
$scope.product = {};
$scope.submitForm = function(product) {
if (product.name) {
formData.updateForm(product);
$state.go('menu.myOrders');
} else {
alert("Please fill out some information for the user");
}
};
})
.controller('myOrdersCtrl', function($scope, formData) {
$scope.product = formData.getForm();
})
services.js
angular.module('app.services', [])
.service('formData', [function(){
return {
form: [],
getForm: function() {
return this.form;
},
updateForm: function(item) {
this.form.push(item);
}
}
}]);
You are inserting same object again and again into the array. As objects are always pass-by-reference so, reference of same object is pushed into array. When you update the object all references stored in array are changed.
Try something like creating copy of your object, while passing to updateForm()
.controller('homeCtrl', function($scope, $state, formData) {
$scope.product = {};
$scope.submitForm = function(product) {
if (product.name) {
formData.updateForm(angular.copy(product));
$state.go('menu.myOrders');
} else {
alert("Please fill out some information for the user");
}
};
})
I'm writing an angular 1.5.0-rc0 application using bootstrap for a nav bar component.
I want to show the user an added items to his navigation bar if his user group id is 1.
first I created a service:
app.factory('UserService', function() {
return {
userGroupId : null
};
});
I created the nav bar as a directive, so i included it in the main html file
<nav-bar></nav-bar>
and the nav-bar directive code:
(function () {
angular.module('myalcoholist').directive('navBar', function () {
return {
restrict: 'E',
templateUrl: 'views/nav.html',
controller: ['$scope','$auth', 'UserService',function ($scope,$auth,UserService) {
$scope.user=UserService;
$scope.isAuthenticated = function()
{
return $auth.isAuthenticated();
};
}]
}
});
})();
as you can see I set $scope.user as the returned object from UserService.
in my login controller, after a successful login I set the userGroupId.
angular.module('myalcoholist').controller('LoginController',['$scope','$auth','$location', 'toastr','UserService',function ($scope,$auth,$location,toastr,UserService) {
$scope.authenticate = function (provider) {
$auth.authenticate(provider).then(function (data) {
var accessToken = data.data.token;
apiKey=accessToken;
UserService.userGroupId=data.data.user_group_id;
...
now.. my nav-bar template file is as the following code:
<li ng-show="user.userGroupId == 1">
Admin Drinks
</li>
even after the authentication, when I uset userGroupId to 1 the element is still not shown.
any ideas?
update
I debugged and noticed that UserService.userGroupId is still null. so
I changed the UserService to have the following code:
app.factory('UserService', function() {
var user = {userGroupId:null};
return {
setUserGroupId: function (userGroupId) {
user.userGroupId=setUserGroupId;
},
getUserGroupId: function () {
return user.userGroupId;
}
};
});
in my LoginController I now try to execute setUserGroupId:
angular.module('myalcoholist').controller('LoginController',['$scope','$auth','$location', 'toastr','UserService',function ($scope,$auth,$location,toastr,UserService) {
$scope.authenticate = function (provider) {
$auth.authenticate(provider).then(function (data) {
var accessToken = data.data.token;
apiKey=accessToken;
UserService.setUserGroupId(data.data.user_group_id);
...
when I debug i see that userService is an object with two functions as I defined, but when the javascript chrome debugger tries to execute this line:
UserService.setUserGroupId(data.data.user_group_id);
I get the following error:
ReferenceError: setUserGroupId is not defined
at Object.setUserGroupId (app.js:21)
at login-controller.js:12
at angular.js:15287
at m.$eval (angular.js:16554)
at m.$digest (angular.js:16372)
at m.$apply (angular.js:16662)
at g (angular.js:11033)
at t (angular.js:11231)
at XMLHttpRequest.v.onload (angular.js:11172)
I have created a fiddle showcasing your requirement (as close as possible), and it seems to work fine.
http://jsfiddle.net/HB7LU/21493/
My guess is that you aren't actually setting the value when you think you are, and will likely require some debugging. Here is the code for brevity.
HTML
<div ng-controller="MyCtrl">
<div ng-click="clicked()">
Click ME, {{user.value}}!
</div>
<test-dir></test-dir>
</div>
JS
angular.module('myApp',[])
.service('TestService', function(){
return {
value: 2
};
})
.directive('testDir', function(){
return {
restrict: 'E',
template: '<div ng-show="user.value === 1">Here is some text</div><div>Some more always showing</div>',
controller: function ($scope, TestService) {
$scope.user = TestService;
}
};
})
.controller('MyCtrl', function($scope, TestService){
$scope.user = TestService;
$scope.clicked = function(){
TestService.value = 1;
};
});