I'm trying to load images from my json file into my application. Here is a code pen: http://codepen.io/beefman/pen/QbBdVw
Here's my code:
js:
.controller('photoCtrl', function($scope, $ionicModal, $ionicBackdrop, $ionicScrollDelegate, $ionicSlideBoxDelegate, $http) {
$scope.images = [];
$scope.getImages = function() {
$http.get('https://api.myjson.com/bins/37ia6')
.success(function(data) {
$scope.images = data.images;
})
}
html:
<ion-view view-title="Gallery" align-title="center" ng-controller="photoCtrl" >
<ion-content ng-init="getImages()" class="center" class="has-header padding">
<!-- start Under6/7/8/9s Photos -->
<div class="item item-divider">
<i class="ion-images"></i> Under6/7/8/9s Photos
</div>
<a class="item item-list-detail">
<ion-scroll direction="x">
<img on-hold="onHold()" ng-repeat="image in images" ng-src="{{images.src}}" ng-click="showImages($index)" class="image-list-thumb" />
</ion-scroll>
</a>
</ion-content>
</ion-view>
You were missing brackets and semicolons in your code.
Use a coding environment to check your syntax, or implement JSHint, which is a tool that checks your code.
http://codepen.io/anon/pen/bdjXYE
angular.module('ionicApp', ['ionic'])
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$ionicConfigProvider.tabs.position('bottom');
$ionicConfigProvider.navBar.alignTitle('center');
$stateProvider
.state('tabs', {
url: "/tabs",
abstract: true,
templateUrl: "tabs.html"
})
.state('tabs.announcement', {
url: '/announcement',
views: {
home: {
templateUrl: 'announcement.html',
controller: 'photoCtrl'
}
}
})
$urlRouterProvider.otherwise('/tabs/announcement');
})
.controller("photoCtrl", function($scope, $http) {
$scope.data = [];
// $scope.getImages = function() {
console.log("trying to load JSON");
$http.get('https://api.myjson.com/bins/1jovy')
.success(function(data) {
$scope.data = data;
console.log(data);
})
.error(function(error) {
console.log(error)
});
});
Related
Maybe someone will help me. I write an app in angularjs, I have a file named list.html which retrieves a list of posts from jsonplaceholder and lists them, with a link to the details of the post. In $ routeParams, I pass the id of the selected one and pick it up. Unfortunately, I have no idea how to download the details of a post and display them in the details.html file. If I want to remove something for example, I write for example $ scope.deletePost as a function and give an id, but how to list details I have no idea.
//routing.js
var myApp = angular.module('myApp', ["ngRoute"])
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/test', {
templateUrl: '/event/example.html',
controller: 'exampleController'
}, null)
.when('/list', {
templateUrl: '/event/list.html',
controller: 'exampleController'
}, null)
.when('/test-list', {
templateUrl: '/test/list.html',
controller: 'testController'
}, null)
.when('/test/:id', {
templateUrl: '/test/details.html',
controller: 'testController'
}, null)
}
]);
//controller.js
angular.module('myApp').controller('testController', function ($scope, $http, $routeParams) {
$http.get('https://jsonplaceholder.typicode.com/posts').then(function (response) {
$scope.posts = response.data;
});
$scope.id = $routeParams.id;
});
//details.html
<div data-ng-controller="testController">
{{data}}
</div>
//list.html
<div data-ng-controller="testController">
<ul>
<li ng-repeat="post in posts">
Tytuł: {{post.title}} <a href="#!test/{{post.id}}" >Show</a>
</li>
</ul>
</div>
Check out this plunkr.
You just need to pass the details using ng-href and then catch in the controller using $routeParams. I hope this would help you with what you were looking for.
var app = angular.module( 'mainApp', ['ngRoute'] );
app.config( function( $routeProvider ) {
$routeProvider
.when( '/main', {
templateUrl: 'list.html',
controller: 'listCtrl'
})
.when('/detail/:id', {
templateUrl: 'detail.html',
controller: 'detailCtrl'
})
.otherwise({
redirectTo: '/main'
});
});
app.controller( 'listCtrl', function( $scope, $http) {
$http.get('https://jsonplaceholder.typicode.com/posts')
.then(function(res){
$scope.data = res.data;
})
});
app.controller( 'detailCtrl', function( $scope,$http, $routeParams) {
$scope.id = $routeParams.id;
$http.get('https://jsonplaceholder.typicode.com/posts/'+$scope.id)
.then(function(res){
$scope.data = res.data;
})
});
I am loading some images from db according to the list item click. Everything works fine but before loading image grid template/state, my ionic framework + angularjs app is opening the default state from $urlRouterProvider.otherwise().
How can I prevent this from happening and directly open image grid state?
list item html:
<ion-list id="fotos-list4" ng-show="albums_list">
<ion-item class="item-icon-left item-icon-right calm" id="fotos-list-item4" ng-model="album_name" ng-repeat="item in albums" item="item" href="#/item/{{item.FOLDER}}" ng-click="open_album(item)">
<i class="icon ion-images"></i>
{{item.FOLDER}}
<i class="icon ion-ios-arrow-forward"></i>
</ion-item>
</ion-list>
image grid html
<div class="row" ng-repeat="image in images" ng-if="$index % 2 === 0">
<div class="col col-50" ng-if="$index < images.length">
<img class="grid-thumb" ng-src="http://website.com/{{images[$index].FILE}}" width="100%" ng-click="showImages($index)" />
</div>
<div class="col col-50" ng-if="$index + 1 < images.length">
<img class="grid-thumb" ng-src="http://website.com/{{images[$index + 1].FILE}}" width="100%" ng-click="showImages($index+1)" />
</div>
</div>
routes.js
angular.module('app.routes', [])
.config(function($stateProvider, $urlRouterProvider) {
// DEFAULT PAGE
.state('cadastreSe', {
url: '/page5',
templateUrl: 'templates/cadastreSe.html',
controller: 'cadastreSeCtrl'
})
// LIST ITEMS
.state('suporte', {
cache: false,
url: '/page7',
templateUrl: 'templates/suporte.html',
controller: 'suporteCtrl'
})
// IMAGE GRID
.state('fotos2', {
cache: false,
url: '/page8',
templateUrl: 'templates/fotos2.html',
controller: 'fotos2Ctrl',
params: {
dataToFotos: false
}
})
$urlRouterProvider.otherwise('/page5')
controller.js
.controller('suporteCtrl', ['$scope', '$http', '$state', function ($scope, $http, $state) {
$scope.open_album = function(item){
var dataToPass = {};
$http.post("http://website.com/select-album-by-name.php", {'album_name': item.FOLDER}).then(function(response){
console.log({'album_name': item.FOLDER});
console.log(response);
console.log(JSON.stringify(response));
dataToPass.item = item;
dataToPass.album = response.data;
$state.go('fotos2', {dataToFotos: dataToPass});
});
}
.controller('fotos2Ctrl', ['$scope', '$state', function ($scope, $state) {
$scope.myGoBack = function(){
$state.go('suporte');
}
if(!$state.params.dataToFotos) {
console.log($state.params.dataToFotos);
alert("Error :(");
}else{
console.log($state.params.dataToFotos);
$scope.images = $state.params.dataToFotos.album;
}
When I am working with complex, or even simple routing in angular/ionic, I like to set up a router module similar to what you have in routes.js. The key is to use the run() function, which will only run when your router module is initialized.
angular.module('myapp.router', [])
.run( [ '$state', '$rootScope', function( $state, $rootScope ) {
// you could set the state directly here
$state.go('mystate');
$rootScope.$on( '$stateChangeStart', function( evt, toState, toParams, fromState, fromParams, options ) {
// or dynamically set the state based on logic here
if( userIsLoggedIn ) {
evt.preventDefault(); // prevent routing
$state.go('user.account'); // go to page
}
});
}]);
What I'm trying to do is create a ui-view for each request in requests.
When the app state = request.detail I'd like to render the "detail" into a UI-view with the id set as the request.id. I cannot figure out how to pass the request.id through angular and name the ui-view which the state renders in dynamically.
For Example if the request.id = 1 I'd like the ui-view to be ui-view="1";
if the request.id=23 , i'd like it's ui-view to be ui-view="23".
Request.js
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', { url: '', views: { 'main': { templateUrl: 'static_pages/home.html'}}})
.state('requests', { url: '/requests', views: {'main': { templateUrl: 'requests.html', controller: 'RequestsCtrl'}}})
.state('requests.detail', { url: '/:id', views: {':id': { templateUrl: function($stateParams) {return `/requests/${$stateParams.id}`;}, controller: 'RequestController'}}})
.state('requests.detail.pdf', { url: '.pdf', views: { 'requestpdf': { templateUrl: function($stateParams) {return `/requests/${$stateParams.id}.pdf`;}, controller: 'RequestController'}}})
.state('requests.detail.edit', { url: '/edit', views: {'main2': { templateUrl: function($stateParams) {return `/requests/${$stateParams.id}/edit`;}, controller: 'RequestController'}}})
.state('users', { url: '/users', templateUrl: 'users.html', controller: 'UsersCtrl'})
.state('/users/:id', { url: 'users_show.html', controller: 'UsersCtrl' });
$locationProvider.html5Mode({ enabled: true, requireBase: false });
});
app.controller("RequestsCtrl", ['$scope', '$state', '$stateParams', 'Request', '$location', function($scope, $stateParams, $state, Request, $location ) {
$scope.requests = Request.query();
$scope.request = Request.query();
$scope.deleteRequest = function (request) {
Request.delete({id: request.id})
console.log("deleted" + request.id);
}
}]);
app.controller("RequestController", ['Request', '$scope', '$stateParams', RequestController]);
function RequestController( $scope, $stateParams, Request ) {
$scope.currentRequestId = $stateParams.request.id;
};
Index.html
<div id='requests' class="requests col-xs-5 col-md-5" ng-controller="RequestsCtrl" >
<div ng-repeat="request in requests" class="request">
<div id="full" ui-view="{{request.id}}"></div>
<a ng-click="showRequest(request);">
<span ng-if="request.read == false"> *NEW*</span>
<span class="col-xs-12">Request #{{request.id}}</span><br>
<span class="col-xs-1">{{request.name}}</span>
<span class="col-xs-1">{{request.email}}</span>
<span class="col-xs-4 col-xs-offset-4">{{request.city}}, {{request.state}}, {{request.region}} </span>
</a>
<div>
<div ng-controller="RequestController">
<a ui-sref="requests.detail({id: request.id})" ng-click="showfullreqest()" ng-init="fullrequest = false">View</a>
<a ng-click="deleteRequest(request)" style="float:left;"> Delete </a>
</div>
</div>
</div>
</div>
I am trying to call a function in another controller from a different controller but but I keep getting error
Error: [ng:areq] Argument 'NewCaseCtrl' is not a function, got undefined
My app.js
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'MainCtrl'
})
.state('app.dashboard', {
url: "/dashboard",
views: {
'menuContent': {
templateUrl: "templates/dashboard.html",
}
}
})
.state('app.new', {
url: "/new_referral",
views: {
'menuContent': {
templateUrl: "templates/new_referral.html",
controller: 'NewCaseCtrl'
}
}
})
my dashboard.html
<ion-view view-title="Dashboard">
<ion-content>
<div class="list card">
<div class="item bar bar-royal">Referral Case Updates</div>
<div class="item item-body">
<div ng-controller="NewCaseCtrl" class="ion-ios-plus-outline" ng-click="createNew()"></div>
</div>
</div>
</ion-content>
</ion-view>
my new_referral.html
<ion-view view-title="New Referral">
<ion-nav-bar class="bar-stable">
<ion-nav-buttons side="left">
<button class="button button-small" ng-click = "goBack()">Cancel</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-content>
<p> In new referral page
</ion-content>
</ion-view>
my new_controller.js
angular.module('my.controllers')
.controller('NewCaseCtrl', function($scope, $rootScope, $q, $window, $ionicModal, createNewRealEstateCase, $state, $ionicLoading, $cordovaCamera, $cordovaFile, $cordovaFileTransfer, $ionicSlideBoxDelegate) {
$scope.createNew = function() {
console.log("in here build loan application")
createNewRealEstateCase.buildLoanApplication().then(function(data){
$rootScope.states = data.states;
$rootScope.nationalities = data.nationalities;
var hideSheet = $ionicActionSheet.show({
buttons: [
{ text: 'Eligibility Checking' },
{ text: 'Loan Application' }
],
cancelText: 'Cancel',
titleText: 'Type of Service',
cancel: function() {
// add cancel code..
},
buttonClicked: function(index) {
console.log(index)
if(index == 0) {
$scope.eligibility = true;
}
else if(index == 1){
$scope.eligibility = false;
}
$state.go('app.new')
return true;
}
});
$timeout(function() {
hideSheet();
}, 10000);
});
};
});
Why do i get an error why i click on the createNew() div in dashboard.html when i have already initiated ng-controller="NewCaseCtrl"? why doesnt it work as it should?
Thanks any help appreciated
Instead of nesting controllers you can have a service which shares the data & functions for both the controller.
I need a Master Detais pattern for my web site. In index lots of thumbnails and every thumbnail link to their detailed page. I make a progress but does not get to work. Its load thumbnails on index oage but when I click to thumbnails its load blank page.
Index:
<body ui-view="viewA">
<div class="row" ui-view="viewB">
<div class="col s12 m6 l4" ng-repeat = "manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerikDetails({id:manga.id})" class="thumbnail">
<img src="/kapaklar/{{manga.kapak}}">
</a>
JS:
angular.module('nasuh',["ui.router"])
.config(function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('index', {
url: "/",
views: {
"viewA": { templateUrl: "index.html",
controller: "indexCtrl",}
}})
$stateProvider
.state('icerik', {
url: "/icerik",
views: {
"viewB": { templateUrl: "icerik.html",
controller: "mmgCtrl",},
}})
$stateProvider
.state('icerikDetails', {
url: "/icerik/:id",
template: "<div>{{details }}</div>",
controller: "mmgCtrl",
resolve: {
getData : function(MY, $stateParams, $filter){
return MY.isimler.then(function(res){
return $filter('filter')(res.data, {id: $stateParams.id}, true)[0];
});}
}
})
$urlRouterProvider.otherwise("/");
})
factory and controllers:
.factory('MY', function($http){
var factory = {};
var url = '/uzak/remote.php?callback=JSON_CALLBACK';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen){
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
$scope.manga = getData.then(function(data){
$scope.details = data;
});})
I am not sure what you are trying to achieve, but at least I tried to convert your snippets into something working.
There is a working example
To get more understanding, do read these:
Nested States and Nested Views
Multiple Named Views
These are states, with a hiererchy. Index is super root, and details is super child:
$stateProvider
.state('index', {
url: "/",
views: {
"": {
templateUrl: "index.tpl.html",
controller: "indexCtrl",
}
}
})
.state('icerik', {
parent: "index",
url: "^/icerik",
views: {
"viewA": {
templateUrl: "icerik.html",
controller: "indexCtrl",
},
}
})
.state('icerik.icerikDetails', {
url: "/icerik/:id",
template: "<div>{{manga}}</div>",
controller: "mmgCtrl",
resolve: {
getData: function(MY, $stateParams, $filter) {
return MY.isimler.then(function(res) {
return $filter('filter')(res.data, {
id: $stateParams.id
}, true)[0];
});
}
}
})
$urlRouterProvider.otherwise("/");
These will be new controllers and factory:
.factory('MY', function($http) {
var factory = {};
//var url = '/uzak/remote.php?callback=JSON_CALLBACK';
var url = 'data.json';
factory.isimler = $http.get(url);
return factory;
})
.controller('indexCtrl', function($scope, MY) {
MY.isimler.success(function(alHemen) {
$scope.mangas = alHemen;
});
})
.controller('mmgCtrl', function($scope, getData) {
//$scope.manga = getData.then(function(data){
// $scope.details = data;
// });
$scope.manga = getData;
})
And an example of templates "index.tpl.html":
<div >
<h2> this is index view</h2>
icerik
<div ui-view="viewA"></div>
</div>
and "icerik.html":
<div class="row" >
<div class="col s12 m6 l4" ng-repeat="manga in mangas">
<div class="row">
<div class="col s5">
<a ui-sref="icerik.icerikDetails({id:manga.id})" class="thumbnail">
img src="/kapaklar/{{manga.kapak}}"
</a>
</div>
</div>
</div>
<hr>
<div ui-view=""></div>
</div>
Check it here