EDIT: image + code + repo
using ionic framwork
Above image is showing how the drawer tab renders the view twice on top of each other.
This happens when in /drawer => /drawer/:itemId/edit' => click on the Drawer tab
it goes back to normal when clicking on the any other tab and going back to the drawer.
my repo is
https://github.com/sebabelmar/lime
this is my app.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: "/tab",
abstract: false,
templateUrl: "templates/tabs.html",
controller: 'TabsCtrl'
})
// Each tab has its own nav history stack:
.state('tab.requests', {
url: '/requests',
views: {
'tab-requests': {
templateUrl: 'templates/tab-requests.html',
controller: 'RequestsCtrl'
}
}
})
.state('tab.drawer', {
url: '/drawer',
views: {
'tab-drawer': {
templateUrl: 'templates/tab-drawer.html',
controller: 'DrawerCtrl'
}
}
})
.state('tab.item-detail-id', { //changed
url: '/drawer/:itemId',
views: {
'tab-drawer': {
templateUrl: 'templates/item-detail-id.html',
controller: 'ItemDetailIdCtrl'
}
}
})
.state('tab.item-detail', { //changed
url: '/drawer/:itemId/edit',
views: {
'tab-drawer': {
templateUrl: 'templates/item-detail.html',
controller: 'ItemDetailCtrl'
}
}
})
.state('tab.account', {
url: '/account',
views: {
'tab-account': {
templateUrl: 'templates/tab-account.html',
controller: 'AccountCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/tab/account');
});
this is my controller
angular.module('starter.controllers', [])
.controller('TabsCtrl', function($scope, User, Items, Requests) {
$scope.userLogged = false;
User.authenticate.then(function() {
console.log(User.loggedIn.username)
Items.sync(User.loggedIn.username);
Requests.sync(User.loggedIn.username);
$scope.userLogged = true;
$scope.user = User.loggedIn;
});
})
.controller('RequestsCtrl', function($scope, User, Sync, Requests) {
Requests.retrieved.then(function(){
$scope.requests = Requests.all;
console.log("from the controller", $scope.requests);
})
//keeps sync with the Factory
setInterval(function(){
$scope.requests = Requests.all },
1000);
})
.controller('ItemDetailIdCtrl', function(){
})
.controller('DrawerCtrl', function($scope, Sync, User, Items) {
var sync;
Items.retrieved.then(function(){
$scope.drawer = Items.drawer;
$scope.items = Items.all;
})
//keeps sync with the Factory
setInterval(function(){
$scope.items = Items.all },
1000);
$scope.newItem = {};
$scope.addToDrawer = function(){
console.log($scope.drawer)
$scope.newItem.owner = $scope.drawer.owner
//adds the item to Items collections
var newItemRef = Sync("items").push($scope.newItem);
itemId = newItemRef.key();
//adds item to the drawer
sync.child(itemId).set("true");
console.log("Item" + $scope.newItem.description + "added with success");
$scope.newItem = {};
}
$scope.isProvider = function(){
if(User.loggedIn.provider)
return false
else
return true
};
$scope.addRequest = function(itemKey){
Sync("requests").push({
item: itemKey,
owner: User.loggedIn.username,
date: Date.now()
})
console.log("Request added")
}
})
.controller('ItemDetailCtrl', function($scope, $stateParams, Sync, User) {
Sync("items").child($stateParams.itemId).on("value", function(snapshot){
$scope.key = snapshot.key();
$scope.item = snapshot.val();
$scope.item_edit = angular.copy($scope.item)
console.log($scope.item)
})
$scope.edit = function(){
Sync("items").child($stateParams.itemId).update({
name: $scope.item_edit.name,
desc: $scope.item_edit.desc,
price: $scope.item_edit.price
})
}
})
.controller('AccountCtrl', function($scope, $q, Sync, Auth, User, Items, Requests) {
var defer = $q.defer();
var sync = Sync("users");
sync.on("value", function(snap){
$scope.users = snap.val();
}, function(errorObject){
console.log("The read failed" + errorObject.code)
})
$scope.newUser = {};
$scope.settings = {
isFemale: true
};
$scope.addNewAuth = function(){
Auth.createUser({
email: $scope.newUser.email,
password: $scope.newUser.password
}, function(error, userData){
if (error) {
console.log("Error creating user" + error);
} else {
$scope.uid = userData.uid;
console.log("Created user authentication for" + $scope.newUser.username)
defer.resolve();
}
})
}
$scope.logIn = function(user){
Auth.authWithPassword({
email: user.email,
password: user.password
}, function(error, authData) {
if(error) {
console.log("Login failed", error)
} else {
console.log("User" + user.email + " has loggedIn", authData);
user_path = "users/" + authData.uid
$scope.authUser();
$scope.loginUser = {};
}
})
}
$scope.register = function(){
$scope.newUser.username = $scope.newUser.email.replace(/#.*/, '')
$scope.addNewAuth();
defer.promise.then(function(){
sync.child($scope.uid).set($scope.newUser)
Sync("drawers").push({owner: $scope.newUser.username})
console.log("User" + $scope.newUser.username + "registered with success")
$scope.logIn($scope.newUser)
$scope.newUser = {};
})
};
$scope.logOut = function(){Auth.unauth();$scope.userLogged=false};
$scope.alwaysHide = function(){return true}
});
this is my drawer where you can click on edit icon to go into item details
<ion-view view-title="Drawer" ng-if="userLogged" >
<ion-header-bar class="bar-stable">
<h1 class="title">Drawer</h1>
<div class="buttons">
<button class="button button-icon ion-plus-circled" ng-click="upload()"></button>
</div>
</ion-header-bar>
<ion-content>
<ion-slide-box on-slide-changed="slideHasChanged($index)" >
<ion-slide ng-repeat="(key, item) in items">
<div class="slide-container">
<div class="item item-avatar" >
<img ng-src="{{item.pic}}">
<h2>{{item.name}}</h2>
<p>{{item.desc}}</p>
<div class='price'>
$ {{item.price}}
<!-- <div class='ion-cash'></div> -->
</div>
</div>
<div class="item-image">
<img class="item-pic" ng-src="{{item.pic}}">
</div>
</div>
<!-- This needs Ng way to do ng class and logic to show and hide -->
<div class="buttons">
<a class="edit-button dark" ng-href="#/tab/drawer/{{key}}/edit" ng-show="isProvider()">
<i class="icon ion-edit"></i>
</a>
<a class="item item-icon-left" href="#" ng-click="addRequest(key)" ng-hide="isProvider()">
<i class="icon ion-code-download"></i>
</a>
</div>
</ion-slide>
</ion-slide-box>
</ion-content>
</ion-view>
here is item detail edit
<ion-view >
<ion-header-bar class="bar-stable">
<h1 class="title">{{item.name}}</h1>
</ion-header-bar>
<ion-content>
<div class="slide-container">
<div class="item item-avatar" >
<img ng-src="{{item.pic}}">
<h2><input type="text" value="{{item.name}}" ng-model="item_edit.name"></h2>
<p><input type="text" value="{{item.desc}}" ng-model="item_edit.desc"></p>
<p id='dollar'>$</p>
<div class='price-edit'>
<label class="price-label item-input">
<input class="price-input" type="text" value="{{item.price}}" ng-model="item_edit.price">
</label>
</div>
</div>
<div class="item-image">
<img class="item-pic" ng-src="{{item.pic}}">
</div>
</div>
<div class=" buttons">
<div class="button-edit">
<a class="edit-button dark" href='' ng-click="edit()">
<i class="icon ion-edit"></i>
</a>
</div>
</div>
</ion-content>
</ion-view>
thanks for reading :D if there is any more info you need inorder to solve my issue i ll gladly provide but i have posted my repo up top
Related
The $scope data is not displaying on the page.
I have 2 views that are using the same controller.
I have this view, and I'm clicking the edit issue button
<div class="container" data-ng-init="adminInit()">
<div class="row">
<div class="col-lg-12">
<div class="page-header text-center">
<h1>Issues Admin</h1>
<button type="button" class="btn btn-primary" ui-sref="add-issue">
Add Issue
</button>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3>Current Issues</h3>
<ul ng-repeat="issue in issues">
<li>
<strong>{{issue.title}}</strong> - Current Status:
<strong>{{issue.status}}</strong>
<div ng-hide="true" class="btn btn-xs btn-primary glyphicon glyphicon-pencil" ng-click="editIssue(issue._id)"></div>
<div class="btn btn-xs btn-primary glyphicon glyphicon-pencil" ng-click="editIssue(issue._id)"></div>
<div class="btn btn-xs btn-danger glyphicon glyphicon-remove" ng-click="deleteIssue(issue._id)"></div>
</li>
<ul>
<li>{{issue.description}}</li>
<li>Issue Logged at: {{issue.timestamp | date:'MM/dd/yyyy # h:mma'}}</li>
</ul>
</ul>
</div>
</div>
</div>
And this in my controller
$scope.editIssue = function(id) {
$state.go('edit-issue');
$http.get(Configuration.API + 'api/issue/' + id)
.then(function successCallback(response) {
$scope.issueToEdit = response.data;
console.log($scope.issueToEdit);
});
};
then the edit-issue view
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="page-header text-center">
<h1>Edit Issue</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form name="frm" ng-submit="updateIssue()">
<div class="form-group">
<label for="editIssueTitle">Issue Title</label>
<input type="text" name="editIssueTitle" id="editIssueTitle" class="form-control" ng-model="issueToEdit.title" required/>
</div>
<div class="form-group">
<label for="editIssueDesc">Issue Description</label>
<textarea name="editIssueDesc" id="editIssueDesc" class="form-control" cols="60" rows="16" ng-model="issueToEdit.description" required></textarea>
</div>
<div class="form-group">
<label for="editIssueStatus">Issue Status</label>
<select name="editIssueStatus" id="editIssueStatus" class="form-control" ng-model="issueToEdit.status" required>
<option value="Identified">Identified</option>
<option value="Investigating">Investigating</option>
<option value="Monitoring">Monitoring</option>
<option value="Resolved">Resolved</option>
</select>
</div>
<button class="btn btn-default" ng-disabled="frm.$invalid">Go</button>
</form>
</div>
</div>
</div>
But the issueToEdit data is never displayed
The console.log line displays the right data
{
"_id": "58135b6e3987b8a90c4fc15b"
"title": "Test"
"description": "Testset"
"timestamp": "2016-10-28T14:06:38.284Z"
"status": "Monitoring"
"__v": 0
}
Any idea why this is happening?
EDIT: Let me clarify a little, when I land on the edit-issue page, I want the issueToEdit data to displayed in the form so that I can then update the info and then save it.
EDIT2: Here is my full controller and app.js
app.controller('issuesController', ['$scope', '$http', '$state', '$interval', 'auth', 'Configuration', function($scope, $http, $state, $interval, auth, Configuration) {
$scope.isLoggedIn = auth.isLoggedIn;
$scope.getIssues = function() {
console.log('retrieving issues');
$http.get(Configuration.API + 'api/issue')
.success(function(data) {
$scope.issues = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.addIssue = function() {
var nIssue = {
'title': $scope.newissue.title,
'description': $scope.newissue.description,
'timestamp': new Date(),
'status': $scope.newissue.status
}
$http.post(Configuration.API + 'api/issue', nIssue)
.success(function(data) {
$state.go('admin');
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.editIssue = function(id) {
$state.go('edit-issue');
$http.get(Configuration.API + 'api/issue/' + id)
.then(function successCallback(response) {
$scope.issueToEdit = response.data;
console.log($scope.issueToEdit);
});
};
$scope.updateIssue = function() {
//ToDo add this logic
};
$scope.deleteIssue = function(id) {
$http.delete(Configuration.API + 'api/issue/' + id)
.success(function(data) {
$scope.issues = data;
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.adminInit = function() {
$scope.getIssues();
$interval($scope.getIssues, 60000);
};
$scope.issueInit = function() {
$scope.getIssues();
$interval($scope.getIssues, 60000);
$(".devInfo").text(navigator.userAgent);
$(".flashVersion").text(FlashDetect.raw);
};
}]);
app.js
var app = angular.module('supportWebsite', ['ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/articles');
$stateProvider
.state('home', {
url: '/',
templateUrl: '/pages/issues/index.html',
controller: 'issuesController'
})
.state('admin', {
url: '/admin',
templateUrl: '/pages/issues/admin/index.html',
controller: 'issuesController',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
})
.state('add-issue', {
url: '/admin/add-issue',
templateUrl: '/pages/issues/admin/add.html',
controller: 'issuesController',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
})
.state('edit-issue', {
url: '/admin/edit-issue',
templateUrl: '/pages/issues/admin/edit.html',
controller: 'issuesController',
onEnter: ['$state', 'auth', function($state, auth) {
if (!auth.isLoggedIn()) {
$state.go('login');
}
}]
});
$locationProvider.html5Mode(true);
}]);
Your method tells the $state service to go to another state. That will replace the view by the view associated with the new state, create a new $scope, and a new controller instance using this new $scope.
So whatever you put in the $scope of the current controller is irrelevant and useless: the other state uses another $scope and another controller.
You need to pass the ID of the issue to edit as a parameter of the new state. And the controller of this new state (or one of its resolve functions) should use that ID to get the issue to edit.
If you want to stay on the same view, using the same controller and the same scope, then you shouldn't navigate to another state.
I have this Controller :
(function(){
'use strict';
angular.module('eliteApp').controller('TeamDetailCtrl',['$stateParams',$ionicPopup,'eliteApi',TeamDetailCtrl]);
function TeamDetailCtrl($stateParams ,$ionicPopup , eliteApi){
var vm = this;
//console.log('$stateParams',$stateParams);
//$stateParams are using to access to parameters in the link
vm.teamId = Number($stateParams.id);
eliteApi.getLeagueData().then(function(data){
var team = _.chain(data.teams)
.flatten("divisionTeams")
.find({"id":vm.teamId})
.value();
vm.teamName = team.name;
vm.games = _.chain(data.games)
.filter(isTeamInGame)
.map(function(item){
var isTeam1 = (item.team1Id === vm.teamId ? true : false);
var opponentName = isTeam1 ? item.team2 : item.team1;
var scoreDisplay = getScoreDisplay(isTeam1 , item.team1ScoreDisplay,item2.team2ScoreDisplay);
return{
gamed : item.id,
opponent: opponentName,
time: item.time,
location: item.location,
locationUrl: item.location.locationUrl,
scoreDisplay: item.scoreDisplay,
homeAway: (isTeam1 ? "vs." : "at")
};
})
.value();
vm.teamStanding = _.chain(data.standings)
.flatted("divisionStandings")
.find({"teamId" : vm.teamId})
.value();
})
vm.following = false;
vm.toggleFollow = function(){
if(vm.following){
var confirmPopup = $ionicPopup.confirm({
title: 'Unfollow?',
template: 'Are you sure you want to unfollow?'
});
confirmPopup.then(function(res){
if(res){
vm.following = !vm.following;
}
})
}
else{
vm.following = !vm.following;
}
};
function isTeamInGame(item){
return item.item1Id === vm.teamId || item.team2Id === vm.teamId;
}
function getScoreDisplay (isTeam1 , team1Score , team2Score) {
if (team1Score && team2Score) {
var teamScore = (isTeam1 ? team1Score : team2Score);
var opponentScore = (isTeam1 ? team2Score : team1Score);
var winIndicator = teamScore > opponentScore ? "W: " : "L:";
return winIndicator + teamScore + "-" + opponentScore;
}
else
{
return"";
}
}
};
})
And team-detail.html file :
<ion-view ng-controller="TeamDetailCtrl as vm" title="{{vm.teamName}}">
<ion-content class="has-header">
<div class="card">
<div class="item item-button-right">
<h2>Record: {{vm.teamStanding.wins}}--{{vm.teamStanding.losses}}</h2>
<button class="button button-positive icon-left"
ng-class="{'icon-checkmark-round': vm.following,'ion-plus-round button-outline':!vm.following}" ng-click="vm.toggleFollow()">
{{vm.following ? "Following" : "Not Following"}}
</button>
</div>
</div>
<div class="list">
<a class="item item-icon-right" ng-repeat="game in vm.games" ui-sref=
"app.game({id: game.gameId})">
{{game.opponent}} {{game.scoreDisplay}}
<div class="row">
<div class="col-20 col-center">
<p>{{game.time | date:'m/d/yy'}}</p>
<p>{{game.time | date:'shortTime'}}</p>
</div>
<div class="col">
<h3>{{game.homeAway}} {{game.opponent}}</h3>
<p>{{game.location}}</p>
</div>
<div class="col-20 col-center">
<h4 class="positive">{{game.scoreDisplay}}</h4>
</div>
</div>
<i class="icon ion-chevron-right icon-accessory"></i>
</a>
</div>
</ion-content>
</ion-view>
In this HTML Page when i click on any link it will redirect me to team-detail.html page with the proper id :
<ion-view title="teams" ng-controller="TeamsCtrl as vm">
<ion-content class="has-header">
<div class="list">
<div ng-repeat="division in vm.teams">
<div class="item item-divider item-energized">{{division.divisionName}}</div>
<a class="item item-icon-right" ng-repeat="team in division.divisionTeams"
href="#/app/teams/{{team.id}}">{{team.name}}
<i class="icon ion-chevron-right icon-accessory"></i>
</a>
</div>
</div>
</ion-content>
</ion-view>
I searched a lot but with no solution .
I did not forget to add the link to index.html page .
Routing file app.js :
angular.module("eliteApp" , ["ionic","angular-cache"])
.run(function($ionicPlatform, CacheFactory) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
CacheFactory("leagueDataCache",{storageMode:"localStorage", maxAge:50000 , deleteOnExpire:"aggressive"});
CacheFactory("leaguesCache",{storageMode:"localStorage", maxAge:50000 , deleteOnExpire:"aggressive"});
CacheFactory("myTeamsCache",{storageMode:"localStorage"});
CacheFactory("staticCache",{storageMode:"localStorage"});
});
})
.config(function($stateProvider , $urlRouterProvider){
$stateProvider
.state('home' ,{
abstract: true,
url: "/home",
templateUrl:"app/home/home.html"
})
.state('home.leagues',{
url: "/leagues",
views:{
"tab-leagues":{
templateUrl: "app/home/leagues.html"
}
}
})
.state('home.myteams',{
url: "/myteams",
views:{
"tab-myteams":{
templateUrl: "app/home/myteams.html"
}
}
})
.state('app', {
abstract:true,
url: '/app',
templateUrl:"app/layout/menu-layout.html"
})
.state('app.teams',{
url: "/teams",
views:{
"mainContent":{
templateUrl: "app/team/teams.html"
}
}
})
.state('app.teams-details',{
url: "/teams/:id",
views:{
"mainContent":{
templateUrl: "app/team/team-detail.html"
}
}
})
.state('app.game',{
url: "/game/:id",
views:{
"mainContent":{
templateUrl: "app/game/game.html"
}
}
})
.state('app.standings',{
url: "/standings",
views:{
"mainContent":{
templateUrl: "app/standings/standings.html"
}
}
})
.state('app.locations',{
url: "/locations",
views:{
"mainContent":{
templateUrl: "app/locations/locations.html"
}
}
})
.state('app.rules',{
url: "/rules",
views:{
"mainContent":{
templateUrl: "app/rules/rules.html"
}
}
})
$urlRouterProvider.otherwise('/app/teams');
});
I have to make app for listing recent photos from Flickr with option when click on any image to show that image with tags and comments it contains.
I've made this:
core.module.js
(function () {
'use strict';
angular.module('flickrApp.core', ['ui.router', 'ngResource']);
})();
core.factory.js
(function () {
'use strict';
angular
.module('flickrApp.core')
.factory('flickrImgs', flickrImgs);
flickrImgs.$inject = ['$http'];
function flickrImgs($http) {
var url = 'https://api.flickr.com/services/rest/?method=flickr.photos.getRecent&api_key=415028ef16a31ed8f70f9dc3e90964d1&extras=url_q,url_o,tags&format=json&nojsoncallback=1';
var photos;
var factory = {
getPhotos: getPhotos
};
return factory;
function getPhotos() {
return $http.get(url).then(function (response) {
factory.photos = response.data.photos.photo;
});
}
};
})();
core.controller.js
(function () {
'use strict';
angular
.module('flickrApp.core')
.controller('flickrController', flickrController);
flickrController.$inject = ['flickrImgs', '$location', '$http'];
function flickrController(flickrImgs, $location, $http) {
var fc = this;
fc.showImg = function (id) {
$location.path("/photos/" + id);
console.log(id);
};
flickrImgs.getPhotos().then(function () {
fc.photos = flickrImgs.photos;
});
}
})();
core.router.js
(function () {
'use strict';
angular
.module('flickrApp.core')
.config(config);
config.$inject = ['$stateProvider', '$urlRouterProvider'];
function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('main', {
abstract: true,
views: {
'header': {
templateUrl: 'app/components/core/header.html'
}
}
})
.state('main.home', {
url: '/home',
views: {
'content#': {
templateUrl: 'app/components/core/home.html',
controller: 'flickrController',
controllerAs: 'fc'
}
}
})
.state('main.singleImg', {
url: '/photos/:id',
views: {
'content#': {
templateUrl: 'app/components/core/single-img.html',
controller: 'flickrController',
controllerAs: 'fc'
}
}
});
newPhoto.$inject = ['$stateParams', 'flickrImgs'];
function newPhoto($stateParams, flickrImgs) {
return flickrImgs.get({
id: $stateParams.id
}).$promise;
}
}
})();
home.html
<div class="row col-sm-12 col-md-10 col-md-offset-1">
<div ng-repeat="photo in fc.photos | limitTo:16" class="col-sm-12 col-md-3">
<a href ng-click="fc.showImg(photo.id)">
<img class="thumbnail" ng-src="{{photo.url_q}}" width="100%">
</a>
</div>
</div>
single-img.html
<div class="row col-sm-12 col-md-10 col-md-offset-1">
<div ng-repeat="photo in fc.photos | filter : {id: photo.id} | limitTo: 1" class="col-sm-12 col-md-10 col-md-offset-1">
<a href ng-click="fc.showImg(photo.id)">
<img class="thumbnail" ng-src="{{photo.url_o}}" width="100%">
</a>
<div>Tags:
<button class="btn-primary">
{{photo.tags}}
</button>
</div>
<div>Comments:
<div>
{{photo.comments}}
</div>
</div>
</div>
</div>
When I click on image listed on home page, I want to pass that image to single-img.html template and I get image id in url, but I don't know how to pass it to html.
Any help would be appreciated.
You are missing ui-sref in in home.html
<div class="row col-sm-12 col-md-10 col-md-offset-1">
<div ng-repeat="photo in fc.photos | limitTo:16" class="col-sm-12 col-md-3">
<a ui-sref="main.singleImg({id: photo.id})">
<img class="thumbnail" ng-src="{{photo.url_q}}" width="100%">
</a>
</div>
</div>
// Updated flickrImgs factory method
function getPhotos() {
var deferred = $q.defer();
if (factory.photos) {
deferred.resolve(factory.photos);
} else {
$http.get(url).then(function(response) {
factory.photos = response.data.photos.photo;
deferred.resolve(factory.photos);
});
}
return deferred.promise;
}
// single image state with new controller
.state('main.singleImg', {
url: '/photos/:id',
views: {
'content#': {
templateUrl: 'app/components/core/single-img.html',
controller: 'singleImgController',
controllerAs: 'sic'
}
}
});
// New Controller
angular
.module('flickrApp.core')
.controller('singleImgController', singleImgController);
singleImgController.$inject = ['$stateParams', 'flickrImgs'];
function singleImgController($stateParams, flickrImgs) {
var vm = this;
flickrImgs.getPhotos()
.then(function(photos) {
angular.forEach(photos, function(photo) {
if(photo.id == $stateParams.id) {
vm.photo = photo;
}
})
});
}
// New single-img.html
<div class="row col-sm-12 col-md-8 col-md-offset-2">
<img class="thumbnail" ng-src="{{sic.photo.url_o}}" width="100%">
<div>Tags:
<div class="btn-primary">
{{sic.photo.tags}}
</div>
</div>
<div>Comments:
<div>
{{sic.photo.comments}}
</div>
</div>
</div>
Hope this helps.
I wrote a code for for my app, when a I click on the toggle to reach the second page, the url changes it took me there but nothing is appeared, just a blank page no more,
here is the app.js code
angular.module("BloodDonationApp", [
"ionic",
])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.keyboard) {
cordova.plugins.keyboard.hidekeyboardAccessoryBar(true);
}
if (window.statusBar) {
//org.apache.cordova.statusbar required
statusbar.styleDefault();
}
});
})
//****************ROUTES***************//
.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
abstarct: true,
url: "/home",
templateUrl: "templates/home.html"
})
.state('home.feeds', {
url: "/feeds",
views: {
"tab-feeds": {
templateUrl: "templates/feeds.html"
}
}
})
.state('home.settings', {
url: "/settings",
views: {
"tab-settings": {
templateUrl: "templates/settings.html"
}
}
})
.state('requestDetails', {
url: "/RequestDetails/:id",
view: {
"mainContent": {
templateUrl: "templates/requestDetails.html"
}
}
})
.state('requestDetails.ClientRegister', {
url: "/Client-Register/:id",
view: {
"mainContent": {
templateUrl: "templates/ClientRegister.html"
}
}
});
//if name of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/home/feeds');
})
and here is the html code of the feeds page:
<ion-view ng-controller="FeedsCtrl as vm">
<ion-content class="has-header">
<div class="card" ng-repeat="requests in vm.feeds">
<div class="item item divider" ng-click="toggleGroup(requests)"
ng-class="{active: isGroupShown(requests)}">
<div class="row row-bottom">
<div class="col">
{{requests.type}}
</div>
<div class="col">
{{requests.unitNb}} Units
</div>
</div>
</div>
<div class="item-accordion"
ng-show="isGroupShown(requests)" ng-click="goToDetails()">
<div class="row">
<div class="col-top">
Since 7 s{{requests.Date}}
</div>
<div class="col col-center col-50 col-offset-8">
<br/>{{requests.HospName}}
<br/>
{{requests.Hosplocation}}
</div>
<div class="col col-bottom">
<a class="item item-icon-right">
<div class="row">
<i class="ion-icon ion-pinpoint "></i>
</div>
<div class="row">
{{requests.HospDistance}}4km
</div>
</a>
</div>
</div>
</div>
</div>
</ion-content>
</ion-view>
and the controller for feeds:
(function () {
'use strict';
angular.module('BloodDonationApp')
.controller('FeedsCtrl', ['BloodDonationApi', '$scope', '$state', FeedsCtrl]);
function FeedsCtrl(BloodDonationApi, $scope, $state) {
var vm = this;
//start Data Binding functions//
var data = BloodDonationApi.getRequests();
console.log(data);
vm.feeds = data;
//end Data Binding//
//start Accordion function//
$scope.toggleGroup = function (requests) {
if ($scope.isGroupShown(requests)) {
$scope.shownGroup = null;
} else {
$scope.shownGroup = requests;
}
}
$scope.isGroupShown = function (requests) {
return $scope.shownGroup === requests;
}
$scope.goToDetails = function() {
$state.go('requestDetails', {id : 5});
}
//end Accordion function//
};
})();
but the request details is not appeared after clicking on the toggle its just give a blanck page, the html code :
<ion-view ng-controller="RequestDetailsCtrl as vm">
<ion-content class="has-header">
<div class="card">
<div class="item">
<div class="row">
<div class="col">
{{requests.type}}
</div>
<div class="col">
{{requests.unitNb}} Units
</div>
</div>
<div class="row">
<div class="col">
{{requests.HospName}}
</div>
<div class="col">
{{requests.Hosplocation}}
</div>
<div class="col">
4 Km Away
</div>
</div>
<button class="button button-block button-positive">
Yes, I donate <i class="ion-icon ion-thumbsup"></i>
</button>
<label>
4/5 <i class="ion-icon ion-battery-half"></i>
</label>
<div class="title">
<h3>
Last time I'd donated was since<br /> 4 months
<i class="ion-icon ion-checkmark-round"></i>
</h3>
</div>
</div>
</div>
</ion-content>
</ion-view>
the controller:
(function () {
'use strict';
angular.module('BloodDonationApp')
.controller('RequestDetailsCtrl', ['BloodDonationApi', '$stateParams', '$scope', RequestDetailsCtrl]);
function RequestDetailsCtrl(BloodDonationApi, $stateParams, $scope) {
var vm = this;
var data = BloodDonationApi.getRequests();
console.log(data);
vm.requestDetails = data;
console.log("$stateParams", $stateParams.id);
//end Data Binding//
// Get you request
};
})();
am sure that there is an error with the view code, but m not figuring it out, if anybody can help me plz.
You are inside a nested state when you are tying to load requestDetails so change your state to :
.state('requestDetails', {...})
.state('home.requestDetails', {
url: "/feeds/:id",
views: {
'tab-feeds' :{
templateUrl: "templates/requestDetails.html"
}
}
})
and your method to:
$scope.goToDetails = function() {
$state.go('home.requestDetails', {id : 5});
}
and It's working !
I've fork your git so updated working version is here if you want to pull
I'm trying to share an object between two controllers with a factory. I can store the object correctly but when I try to get it from the main controller it says the object it's empty(undefined). I would appreciate some feedback.
var app = angular.module('wgot', ['ionic'])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('splash', {
url: "/",
templateUrl: "templates/splashscreen.html"
})
.state('settings', {
url: "/settings",
templateUrl: "templates/settings.html"
})
.state('main', {
url: '/main',
templateUrl: 'templates/main.html'
})
$urlRouterProvider.otherwise('/');
})
.factory('TT', function(){
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
})
.controller('SettingsCtrl', function($scope, $http, TT){
$scope.regions = [
{name : 'United Arab Emirates', id : '23424738'}
];
$scope.region = $scope.regions[0];
$scope.requestTT = function() {
$http.get(/* url */ + $scope.region.id).success(function (data){
TT.set(data);
})
};
})
.controller('MainCtrl', function($scope, TT){
//Here TT.get() doesn't return the value that I've stored previously
$scope.words = TT.get();
var words = [];
var listLength = $scope.words.list[0]['trends'].length;
for (var i = 0; i < listLength; i++) {
words[i] = $scope.words.list[0]['trends'][i].name;
};
this.words = words;
});
This are the views:
<ion-view class= "splashscreen" ng-controller="SettingsCtrl">
<ion-content class = "content" scroll="false">
<div class="bar bar-header bar-light">
<h1 class="title">Settings</h1>
</div>
<div class="list card list-card">
<label class="item item-input item-select">
<div class="input-label">
Country
</div>
<select ng-model="region" ng-options="region.name for region in regions">
<option value="">-- choose a region --</option>
</select>
</label>
<a class="item item-icon-right assertive" ui-sref="main" ng-click="requestTT()">
<i class="icon ion-radio-waves"></i>
Start receiving
</a>
</div>
</ion-content>
</ion-view>
This second controller is the one that can't get the object.
<ion-view class = "main">
<ion-content>
<div class="os-phrases" ng-controller="MainCtrl as main">
<h2 ng-repeat="word in main.words" ng-bind-html='word | lettering'></h2>
</div>
</ion-content>
</ion-view>
I think the problem is that by the time you read the data from the service in the Main controller, nothing has been assigned to it yet, one way to work around this would be to watch the data in the service inside your Main controller:
$scope.$watch(TT.get,function(v){
$scope.words = v;
})