I have a little problem with ng-repeat.
I have a json file where is the data that I'm trying to display.
I wrote a little service to share the data. It has some methods to set and get the information but, when I try to use that methods in my controller to store the result in a variable (the one that I'm trying to iterate) it is like is were empty but, when I print the variable, print the result.
Here s my approach.
HTML
<ul class="list-unstyled products-list">
<li class="col-sm-6 col-md-3 product" ng-repeat="product in products">
<article>
<img ng-src="{{ product.img }}" class="img-responsive" alt="">
<div class="short-product-detail text-center">
<p class="name">{{ product.name }}</p>
<span class="price">{{ product.price }}</span>
</div>
add to cart
</article>
</li>
</ul>
controller
angular.module("Store")
.controller("ProductsCtrl", ["$scope", "productsService", function ProductsCtrl($scope, productsService) {
$scope.products = [];
productsService.fetchProducts()
.then(function(response) {
productsService.setProducts(response.data.products);
$scope.products = productsService.getProducts();
console.log($scope.products)
})
}])
service
angular.module("Store")
.service("productsService", ["api", "$http", function (api, $http) {
var productsList = [];
var categories = [];
var getProducts = function() {
return productsList;
};
var setProducts = function(products) {
productsList.push(products);
};
var getCategories = function() {
return categories;
};
var setCategories = function(categories) {
categories.push(categories);
}
var fetchProducts = function() {
return $http({
method: "GET",
url: api.url
});
}
return {
fetchProducts: fetchProducts,
getProducts: getProducts,
setProducts: setProducts,
getCategories: getCategories,
setCategories: setCategories
}
}])
main.js
angular.module("Store", ["ui.router"])
.constant("api", {
url: "data.json"
})
.config(function config($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
// Set up the states
$stateProvider
.state("products", {
url: "/",
views: {
"": {
templateUrl: "./templates/products.html",
controller: "ProductsCtrl"
}
}
})
})
Please, let me know what I'm doing wrong.
Thanks in advance guys
Problem is with your config, Change it like this
$stateProvider
.state('products', {
url: '/products',
templateUrl: './templates/products.html',
controller: 'ProductsCtrl'
})
Related
I'm trying to make a Master-Detail module, but is not working. When I tap on the link that should go to the detail page, nothing happens, and in the console doesn't show any error. I'm working over a template created by Ionic Creator.
These are my controllers:
.controller('administraciNCtrl', ['$scope', '$stateParams','obtenerPerfiles', function ($scope, $stateParams,obtenerPerfiles) {
var initView = function(){
$scope.perfiles = obtenerPerfiles.query();
//console.log('Scope es:',$scope);
}
$scope.$on('$ionicView.loaded',function(){
initView();
});
}])
.controller('profesionalDetailCtrl', function ($scope, perfil) {
var initView = function(perfil){
$scope.perfil = perfil;
//console.log('Scope es:',$scope);
}
$scope.$on('$ionicView.loaded',function(){
initView();
});
})
This is the factory:
.factory('obtenerPerfiles', function($resource){
var getProfile = {};
getProfile.getPerfil = function(nombrePerfil){
/*I will use nombrePerfil later, first I wanna test it works*/
var datos;
datos = {"nombre": "yuyu","direccion":"carrera 11","perfil":"Administradorcita"};
return datos;
};
return $resource('bd/administracion.json', {}, { query: {method:'GET', isArray:true}});
});
This is the state:
.state('cONSTRYELO2.administraciN', {
url: '/page7',
views: {
'side-menu21': {
templateUrl: 'templates/administraciN.html',
controller: 'administraciNCtrl'
}
}
})
.state('cONSTRYELO2.profesionalDetail', {
url: '/perfilDetalle/:nombrePerfil',
views: {
'side-menu21': {
templateUrl: 'templates/profesionalDetail.html',
controller: 'profesionalDetailCtrl',
resolve:{
perfil: function($stateParams,obtenerPerfiles){
return obtenerPerfiles.getPerfil($stateParams.nombrePerfil);
}
}
}
}
})
And finally this is the HTML:
<ion-item class="item-icon-left item-icon-right" id="administraciN-list-item47" ui-sref="cONSTRYELO2.profesionalDetail({nombrePerfil:'{{perfil.nombre}}'})">
<i class="icon ion-android-globe"></i>3km
<span class="item-note">Ver más</span>
<i class="icon ion-android-add-circle"></i>
</ion-item>
heres my code, i try to show my selected product form my product page by id.
for example when i click a product it go to right url like /#/product/2 and it show all the attribute of product id:2. please take a look this code
app.js
angular
.module('app', [
'ui.router',
'app.directives.productCard'
])
.config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'templates/pages/home.html',
controller: 'homeCtrl'
})
.state('product', {
url: '/product',
templateUrl: 'templates/pages/product.html',
controller: 'productCtrl'
})
.state('productDetails', {
url: '/product/:id',
templateUrl: 'templates/pages/productDetails.html',
controller: 'productDetailsCtrl'
})
}])
my services
angular
.module('app')
.factory('Product', ['$http', function($http) {
return {
get: function() {
return $http.get('https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json').then(function(response) {
return response.data;
});
}
};
}])
productCtrl
angular
.module('app')
.controller('productCtrl',['$scope', 'Product', function($scope,Product) {
$scope.title="List Product";
Product.get().then(function(data) {
$scope.products = data;
});
$scope.products=Product.get();
}]);
productdetailsCtrl
angular
.module('app')
.controller('productDetailsCtrl',['$scope','$stateParams', 'Product', function($scope,$stateParams,Product){
$scope.id=$stateParams.id;
Product.get().then(function(data) {
var singleProduct = data.filter(function(entry){
return entry.id === $scope.id;
})[0];
console.log(singleProduct);
console.log($stateParams);
});
}]);
product.html
<div class="col-lg-3 col-md-4 col-sm-6">
<div class="card">
<img class="card-img-top" ng-src="{{item.image}}" alt="{{item.name}}">
<div class="card-block">
<strong class="card-title">{{item.name}}</strong>
</div>
<div class="card-block">
Buy
</div>
</div>
</div>
product detail.html
<p>{{id}}</p>
<p>{{name}}</p>
<p>{{image}}</p>
after all this code,when i try to check via console. i get Object {id: "2"}, but when i try to show all the attribute from product 2 i get on console undefined. why i got undifined. yeah i didnt use and local server. but if its the problem. does all the code is right to print all the attribut of product 2
here the link of the json https://raw.githubusercontent.com/vicariosinaga/learn/master/products.json
Change product details state url to make id parameter as a int which will allow you to pass return entry.id === $scope.id;(strict equality check).Here you have id value as string which makes singleProduct as undefined.
.state('productDetails', {
url: '/product/{id:int}',
templateUrl: 'templates/pages/productDetails.html',
controller: 'productDetailsCtrl'
})
otherwise you have to change your strict check to return entry.id == $scope.id;
I am working in MEAN stack. For my front-end, I am trying to render data of single item from my item list with angular. When I click the item, the URL changes to other than I have set and I don't get the data. I was able to see this only after using debugging mode. The expected link is /item/:itemid but I am getting /item/partials/item.html I have used the following files:
main.route.js (only route with problem shown)
function config($routeProvider, $locationProvider) {
$routeProvider
.when('/item/:itemid', {
templateUrl: 'partials/item.html',
controller: 'productCtrl',
controllerAs: 'vm'
})
.otherwise({redirectTo: '/'});
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
};
myData.service.js
angular
.module('myApp')
.service('myData', myData);
function myData ($http) {
var itemById = function (itemid) {
return $http.get('/api/items/' + itemid);
};
return {
itemById : itemById
};
}
product.controller.js
angular
.module('myApp')
.controller('productCtrl', productCtrl)
function productCtrl($routeParams, myData) {
var vm = this;
vm.itemid = $routeParams.itemid;
myData.itemById(vm.itemid)
.success(function(data) {
vm.data = { item : data };
vm.pageHeader = {
title: vm.data.item.name
};
})
.error(function (e) {
console.log(e);
});
};
items.html (link to single item page)
<a href='/#/item/{{ item._id }}'>{{ item.name }}</a>
item.html
<div ng-controller='productCtrl'>
<div class='container'>
<page-header content='vm.pageHeader.title'></page-header>
</div>
</div>
Forgive me if the question doesn't make much sense as I am new to this. Thanks in advance!
Remove the slash on this anchor below:
<a href='#/item/{{ item._id }}'>{{ item.name }}</a>
Given that I am going to the following state:
$stateProvider.state('applicant', {
url: "/admin/applicants/:name",
templateProvider: function($http, $stateParams) {
return $http({
method: 'GET',
url: 'http://example.com/applicant',
params: {
request: $stateParams.name,
}
}).then(function successCallback(html) {
return html.data;
});
},
controller: 'SendToCtrl'
});
With the view that is being returned by $http looking like this:
<script>
app.controller('ChildController', ['$scope', function($scope) {
$scope.applicant = <?php echo $applicant ?>;
}]);
</script>
<div class="row" ng-controller="ChildController">
<div class="col-md-12">
{{applicant.State}}
</div>
</div>
I get a Argument 'ChildController' is not a function error. I read that in the regular ng-view calling a new controller like this is not supported, but couldn't find an answer for ui-router. What would be the proper way to do templating then if I need the template to display data that is only there once the view is served?
So I couldn't generate the controller from within the view like I wanted, so instead I used the controller generated by the state and attached the php variable to the view, then picked it back up again from said set controller, like so:
State Definition:
$stateProvider.state('applicant', {
url: "/admin/applicants/:name",
templateProvider: function($http, $stateParams) {
return $http({
method: 'GET',
url: 'http://example.com/applicant',
params: {
request: $stateParams.name,
}
}).then(function successCallback(html) {
return html.data;
});
},
controller: 'SendToCtrl'
});
View:
<?php
$applicant = str_replace('"', "'", $applicant);
?>
<div class="row">
<div id="fetchMe" class="col-md-12">
</div>
</div>
<script>
applicant = <?php echo $applicant ?>;
$('#fetchMe').data('key',applicant);
</script>
SendToCtrl:
app.controller('SendToCtrl', ["$scope", "$stateParams", "$state", function($scope, $stateParams, $state) {
console.log($stateParams);
$scope.applicant = $("#fetchMe").data('key');
console.log($scope.applicant);
}]);
:)
i was making a gallery using angular, i categorized images so when the gallery loads, each category is represented by an image, when user clicked on the image they would see the entire images of that gallery.
for that i made an array so each image representing a category has a block that is an array and consist information of all images in that category. and using that block for loading those images.
so i was trying to use $routeParams so i could make a url for each category to load data in that view, the representative image of categories are loading fine but i can't load the images of that category in the view.
my module code is:
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'contentsCtrl',
templateUrl: 'views/contents.php'
})
.when('/news/', {
controller: 'newsCtrl',
templateUrl: 'views/news.php'
})
.when('/notes/', {
controller: 'notesCtrl',
templateUrl: 'views/notes.php'
})
.when('/records/', {
controller: 'recordsCtrl',
templateUrl: 'views/records.php'
})
.when('/gallery/', {
controller: 'galleryCtrl',
templateUrl: 'views/gallery.php'
})
.when('/gallery/:galleryID', {
controller: 'imagesCtrl',
templateUrl: 'views/images.php'
})
.when('/statute/', {
controller: 'statuteCtrl',
templateUrl: 'views/statute.php'
})
.when('/forms/', {
controller: 'formsCtrl',
templateUrl: 'views/forms.php'
})
.when('/about/', {
controller: 'aboutCtrl',
templateUrl: 'views/about.php'
})
.when('/contact/', {
controller: 'ContactCtrl',
templateUrl: 'views/contact.php'
})
.when('/post/', {
controller: 'PostCtrl',
templateUrl: 'views/post.php'
})
.otherwise({redirectTo: '/'});
});
and the code for the controller is:
(function () {
var imagesCtrl = function ($scope, $http, $routeParams) {
$http.get("includes/gallery.php").success(function (response) {
$scope.gallery = response.gallery;
});
var galleryID = $routeParams.galleryID;
$scope.images = $scope.gallery[0];
function init() {
// Search gallery for the galleryID
for (var i = 0, len = $scope.gallery.length; i < len; i++) {
if ($scope.gallery[i].imageCategory == parseInt(galleryID)) {
$scope.images = $scope.gallery[i].category;
break;
}
}
}
init();
};
imagesCtrl.$inject = ['$scope', '$http', '$routeParams'];
angular.module('myApp').controller('imagesCtrl', imagesCtrl);
}());
and this is the view:
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ galleryID }}</h1>
</div>
Back to Gallery
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 thumb" ng-repeat="image in images">
<img class="img-responsive" src="./uploads/images/{{ image.imageName}}" alt="" style="width:400px; height:160px;">
</div>
so anyone knows what is the problem? i would appreciate the help!
You're calling your init() function just after sending the $http request. It thus tries finding the gallery in $scope.gallery, but $scope.gallery is initialized long after, when the response to the $http request is available.
The code should be:
$http.get("includes/gallery.php").success(function (response) {
$scope.gallery = response.gallery;
init();
});
function init() {
// Search gallery for the galleryID
for (var i = 0, len = $scope.gallery.length; i < len; i++) {
if ($scope.gallery[i].imageCategory == parseInt($routeParams.galleryID)) {
$scope.images = $scope.gallery[i].category;
break;
}
}
}
That said, Why do you get all the galleries from the server for each page, supposed to render a single gallery. You should send the gallery ID to the server, and the server should respond with that category only, instead of always responding with all the galleries.
Another approach is to use $routerresolve, the router will wait for these promises to be resolved or one to be rejected before the controller is instantiated.
Route Setup:
.when('/gallery/', {
controller: 'galleryCtrl',
templateUrl: 'views/gallery.php'
resolve: {
gallery: ['$http', function($http) {
return $http
.get('includes/gallery.php')
.then(
function success(response) {
return response.data;
},
function error(reason) {
return false;
}
);
}
]
}
})
The controller should looks like this:
(function (angular) {
var imagesCtrl = function ($scope, $http, $routeParams, gallery) {
$scope.gallery = gallery;
var galleryID = $routeParams.galleryID;
$scope.images = $scope.gallery[0];
function init() {
// Search gallery for the galleryID
for (var i = 0, len = $scope.gallery.length; i < len; i++) {
if ($scope.gallery[i].imageCategory == parseInt(galleryID)) {
$scope.images = $scope.gallery[i].category;
break;
}
}
}
init();
};
imagesCtrl.$inject = ['$scope', '$http', '$routeParams', 'gallery'];
angular.module('myApp').controller('imagesCtrl', imagesCtrl);
}(angular));