I have a Json that contains this:
[
{
"_id": "00000",
"title": "",
"genre": "fantasy",
"year": "1999",
"image": "photo.jpg"
}
]
I use AngularJs and I want show image in my page html. This is the code:
<div>
<h2>Films</h2>
<div>
<div ng-repeat="book in lista">
<div>
<img ng-src="{{book.cover}}" style="width: 256px; height: 128px;">
</div>
</div>
</div>
</div>
and this is my controller:
var modulo = angular.module('progetto', ['ngRoute']);
modulo.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'list.html',
controller: 'listController'
})
});
modulo.controller('listController', function ($scope, $http) {
$http.get('http://.......').success(function (data) {
$scope.lista = data;
}).
error(function (data, status) {
$scope.lista = "Request failed";
});
});
how do I show the photo? Because the photo is a jpg. Thanks!
You might want to call $scope.$apply() after every http request which are modifying the model and the new value needs to be communicated to the view.
lo.controller('listController', function ($scope, $http) {
$http.get('http://.......').success(function (data) {
$scope.lista = data;
$scope.$apply();
}).
error(function (data, status) {
$scope.lista = "Request failed";
$scope.$apply();
});
});
Related
You will have to bear with me because I am a self-taught noob.
I have a php page on my server that need a $_get variable to sort the data on the server side rather than the client. I am using routeParams in Angular for the variable to send over. This works, however it only works when you refresh the webpage. Please can someone help me as my head hurts from hitting the wall.
Controller:
app.controller('JuiceController', ['$scope', 'juices', function($scope, juices) {
juices.success(function(data){
$scope.juices = data;
});
}]);
Service:
app.factory('juices', ['$http', '$routeParams',function($http, $routeParams) {
return $http.get('http://madcow-app.dev/application/backend/api/products.php', {
params: {prod: $routeParams.prod}
})
.success(function(data) {
return data;
})
.error(function(err){
return err;
});
}]);
Html output (juice view):
<div class="juice-wrap" ng-repeat="juice in juices">
<div class="juice-img"><img ng-src="{{ juice.imgpath }}" width="163" height="176" alt=""/></div>
<div class="juice-rght">
<div class="juice-title">{{ juice.name }}</div>
<div class="juice-desc">{{ juice.descrip }}</div>
Route provider
$routeProvider
.when('/', {
templateUrl: 'script/views/home.html'
})
.when('/categories/', {
controller: 'CatController',
templateUrl: 'script/views/categories.html'
})
.when('/juice/:prod', {
controller: 'JuiceController',
templateUrl: 'script/views/juice.html'
})
.when('/events/', {
controller: 'EventController',
templateUrl: 'script/views/events.html'
})
.when('/qr/', {
templateUrl: 'script/views/qr.html'
})
.when('/feedback/', {
templateUrl: 'script/views/feedback.html'
})
.otherwise({
redirectTo: '/'
php function outputs json (this is outputted to the php controller below and takes the category id as a variable:)
return json_encode($results);
To the php controller (this is the page that the angular service/factory pulls the json array of products from:
<?php
include "../../init.php";
if (isset($_GET['prod']))
{
echo $MC->Api->getProductsApi($_GET['prod']);
}
else
{
echo 'error';
}
This is the category html:
<div class="cat-btn" ng-repeat="cat in cats">
<a href="#/juice/{{cat.catid}}">
<img ng-src="{{ cat.imgpath }}" width="363" height="195" alt=""/>
<div class="cat-btn-text"> {{ cat.name }} </div>
</a>
basically what I want to achieve is when a user clicks a category in the frontend, angular routes to the product view using the category id as a filter for the php function to populate the json output with only the juices in that category.
I'm not sure if I should be doing it this way around, or whether I need to hit it from another angle. Please bear in mind that i am a complete javascript noob and laymans would be great for the answer.
Thank you in advance.....
Factory:
app.factory('juices', [
'$http', '$routeParams', function ($http, $routeParams) {
var self = this;
function getJuices() {
$http.get('http://madcow-app.dev/application/backend/api/products.php', {
params: {prod: $routeParams.prod}
})
.success(function (data) {
self.juices = data.data;
})
.error(function (err) {
});
}
return {
getJuices: getJuices,
juices: self.juices
}
}
]);
Controller:
app.controller('JuiceController', [
'$scope', 'juices', function ($scope, juices) {
juices.getJuices();
$scope.$watch(function () {
return juices.juices
}, function (newJuices, oldJuices) {
// This is triggered when juices.juices changes
// newJuices containes the juices retrieved from server
// This is needed because it is asynchronous
});
}
]);
I am stuck in the last part of this Codecademy AngularJs project
I have used routing and the routing works (it changes the view when clicked), but doesn't show data binding. I have checked index.html so I don't think there's a mistake there. Could you please check it? Here is the code:
app.js
var app = angular.module('CalendarApp', ['ngRoute'])
app.config(['$routeProvider', function($routeProvider) {
$routeProvider .when('/', {
controller: 'DayController',
templateUrl: 'views/day.html'
}).when('/:id',{
controller: 'EventController',
templateUrl: 'views/event.html'
}).otherwise({
redirectTo: '/'
});
}]);
events.js (Service)
app.factory('events', ['$http', function($http) {
return $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/events-api/events.json').success(function(data) {
return data;
}).error(function(err) {
return err;
});
}]);
EventController.js
app.controller('EventController', ['$scope', 'events', '$routeParams', function($scope, $routeParams, events) {
$scope.eventId = $routeParams.id;
events.success(function(data) {
$scope.event = data.events;
});
}]);
event.html (view)
<div class="event-detail">
<h2 class="event-name">{{event[eventId].name}}</h2>
</div>
And here's the short format of events.json whose data I'm trying to get:
{
"date": 1421384400000,
"events": [
{
"name": "Casual Friday",
"from": 1421384400000,
"to": 1421470800000,
"where": ""
},
{
"name": "Taco Time",
"from": 1421431200000,
"to": 1421438400000,
"where": "Brooklyn Taco Co. 120 Essex Street New York, NY 10002"
}
]
}
events.js
try returning promise, but load it only once;
app.factory('events', ['$http', function($http) {
var promise = $http.get('https://s3.amazonaws.com/codecademy-content/courses/ltp4/events-api/events.json');
return {
getEvents : function(){ return promise; }
}
}]);
Now if you console.log it you should recieve Promise object in your controller.
EventController.js
app.controller('EventController', ['$scope', 'events','$routeParams', function($scope, events, $routeParams) {
// code in regards to itemId etc.
events.getEvents().then(function(d){
$scope.event = d.data.events;
});
}]);
(considering rest of the functionality works as you mentioned)
Let me know if it works
I am receiving a JSON object from WordPress which looks like this
{
"ID": 4164,
"title": "24 Horas Non-Stop con Marco Carola",
"status": "publish",
"type": "post",
"author": {
"ID": 11,
"username": "VIlma Quiros",
"registered": "2015-04-16T07:04:04+00:00",
"meta": {
"links": {
"self": "http://urbanetradio.com/wp-json/users/11",
"archives": "http://urbanetradio.com/wp-json/users/11/posts"
}
}
},
"content": "<p class=\"p2\"><a href=
here is my service
.service('FreshlyPressed', function($http, $q) {
return {
getBlogs: function($scope) {
var posts = [];
$http.get('http://urbanetradio.com/wp-json/posts')
.success(function(result) {
$scope.posts = result;
})
},
getPostById: function(postId) {
var url ='http://urbanetradio.com/wp-json/posts/postId';
return $http.get(url);
}
});
and here the controller
.controller('NewsCtrl', function($scope, FreshlyPressed) {
$scope.posts = [];
$scope.doRefresh = function() {
$scope.posts = FreshlyPressed.getBlogs($scope);
$scope.$broadcast('scroll.refreshComplete');
}
$scope.doRefresh();
});
and here is what I want:
in this view I display only the title and the date of the posts, this is the main view
<a ng-href="#/tabs/news/{{post.ID}}">
<h2 ng-bind-html="post.title"></h2>
<p>{{:: post.date | date}}</p>
</a>
when you click in that title you should be redirected to the entired post which is here, in the secondary view
<div class="item item-text-wrap item-image padding">
<div class="special-font" ng-bind-html="post.content"></div>
</div>
the routes
//the route for the main view
.state('tabs.news', {
url: '/news',
views: {
'tab-news': {
templateUrl: 'templates/tab-news.html',
controller: 'NewsCtrl'
}
}
})
//the route for the second view where you will see the entire post
.state('tabs.post-detail', {
url: '/news/:postId',
views: {
'tab-news': {
templateUrl: 'templates/tab-post-detail.html',
controller: 'PostDetailCtrl'
}
}
})
I get this error
GET http://urbanetradio.com/wp-json/posts/postId 404 (Not Found)
I guess you need to change this function like this
getPostById: function(postId) {
var url ='http://urbanetradio.com/wp-json/posts/'+ postId;
return $http.get(url);
as per you code postId is parameter that you want to replace in string than you should append value in string as in code
you need to call method like
FreshlyPressed.getPostById(1);//1 is postid value
Angular newbie here, Trying to render a list of json content in the template. Using Angular 1.0.5.
Here is the app.js
var Task = angular.module("Task", ["ui.bootstrap", "ngCookies"]);
Task.config(function ($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "static/js/app/views/todolist.html",
controller: "TaskListController",
resolve: {
tasks: function (ToDoService) {
return ToDoService.list();
}
}
})
........
Here is the TaskListController:
Task.controller('TaskListController', function ($scope, GlobalService, ToDoService, tasks) {
$scope.tasks = tasks;
console.log("tasks");**// this does not get logged. Any reason why?**
$scope.globals = GlobalService;
});
ToDoService -
Task.factory('ToDoService', function ($http, $q) {
var api_url = "/todo/";
return {
list: function () {
var defer = $q.defer();
$http({method: 'GET', url: api_url}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
defer.reject(status);
});
return defer.promise;
},
And the view goes here -
<div class="content" ng-repeat="task in tasks">
<a class="clip-open" href="{{task.api_url}}">
<h3>{[{task.title}]}</h3>
</a>
<div class="meta clips-note">
<p>
{{task.description|truncate:150}}
</p>
</div>
<p>
<small><abbr time-ago title="{{post.assigned_time}}" class="date"></abbr></small>
<small><b>by</b> {{task.kreator}}</small>
</p>
</div>
</div>
</div>
The server at /todo/ is returning a list of todos in JSON format. But in my browser, I can't see the data. What am I missing?
Please ignore all missing semi-colons and missing parenthesis.
Assume all the files have been imported.
The name of your resolve is "todos"
resolve: {
todos: function (ToDoService) {
return ToDoService.list();
}
}
However, you are injecting tasks into your controller (which I don't see defined):
Task.controller('TaskListController', function ($scope, GlobalService, ToDoService, tasks) {
$scope.tasks = tasks;
$scope.globals = GlobalService;
});
I think you need to inject todos into your controller to access them.
I am starting out on the angular seed. I have a json file that displays items like the below.
{
"id":"1",
"name":"Spain",
"abbrev":"esp"
}
When I click on a country in the list I want to the display the details such as the name for this item.
I have this working as shown below.
/* app.js */
'use strict';
// Declare app level module which depends on views, and components
angular.module('myApp', ['ngRoute','myApp.controllers','myApp.services'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryCtrl'
});
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/:name', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
});
}])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/'});
}]);
/* services.js */
angular.module('myApp.services', [])
.factory('Countries', ['$http', function($http) {
var Countries = {};
Countries.name = '';
Countries.listCountries = function () {
return $http.get('../api/countries');
},
Countries.ChangeName = function (value) {
Countries.name = value;
}
return Countries;
}]);
/* controllers.js */
angular.module('myApp.controllers', [])
.controller('CountryCtrl', ['$scope', 'Countries', '$location', function($scope, Countries,$location) {
listCountries();
function listCountries() {Countries.listCountries()
.success(function (data, status, headers, config) {
$scope.countries = data.countries;
})
.error(function(data, status, headers, config) {
$scope.status = 'Unable to load data: ' + error.message;
});
}
$scope.name = Countries.name;
$scope.changeView = function(countryName,indx){
$location.path(countryName);
$scope.name = Countries.ChangeName(countryName);
}
}]);
/* templates/view1.html */
<ul>
<li ng-repeat="country in countries">
<div ng-click="changeView(country.name,$index)">{{country.name}}</div>
</li>
</ul>
/* templates/view2.html */
{{name}}
What I can't get to work is that if I go to http://www.example.com/app/#/ then navigate to spain in the list then I get taken to http://www.example.com/app/#/esp and {{name}} gets outputted as esp.
However if I navigate straight to http://www.example.com/app/#/esp without first clicking on spain in the list I get no value in my $scope.name
How can I achieve this?
I want the name to also be set based on the location path if it is available.
I know that $location.$$path will get me /esp however I don't really think this is the best idea to use this incase the url builds out to something bigger eg http://www.example.com/app/#/esp/events
can I some how access the index or id of the item so that I can then access the data like
{{countries[0].name}}
where 0 is id of esp - 1.
What is the best approach?
Mate, there are a couple of issues with your app.
Your service retains "state" although is only used to retrieve information
You're using the same controller to 2 different views (bad practice)
$scope.status = 'Unable to load data: ' + error.message; --> Error is not defined
There are a couple of js errors too, like strayed commas and stuff
Anyways, here's a revised version of your code. Fiddle
// Instantiate your main module
var myApp = angular.module('myApp', ['ngRoute']);
// Router config
myApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'templates/view1.html',
controller: 'CountryListCtrl'
})
.when('/:id', {
templateUrl: 'templates/view2.html',
controller: 'CountryCtrl'
})
}
]);
// Your Factory. Now returns a promise of the data.
myApp.factory('Countries', ['$q',
function($q) {
var countriesList = [];
// perform the ajax call (this is a mock)
var getCountriesList = function() {
// Mock return json
var contriesListMock = [{
"id": "0",
"name": "Portugal",
"abbrev": "pt"
}, {
"id": "1",
"name": "Spain",
"abbrev": "esp"
}, {
"id": "2",
"name": "Andora",
"abbrev": "an"
}];
var deferred = $q.defer();
if (countriesList.length == 0) {
setTimeout(function() {
deferred.resolve(contriesListMock, 200, '');
countriesList = contriesListMock;
}, 1000);
} else {
deferred.resolve(countriesList, 200, '');
}
return deferred.promise;
}
var getCountry = function(id) {
var deferred = $q.defer();
if (countriesList.length == 0) {
getCountriesList().then(
function() {
deferred.resolve(countriesList[id], 200, '');
},
function() {
deferred.reject('failed to load countries', 400, '');
}
);
} else {
deferred.resolve(countriesList[id], 200, '');
}
return deferred.promise;
}
return {
getList: getCountriesList,
getCountry: getCountry
};
}
]);
//Controller of home page (pretty straightforward)
myApp.controller('CountryListCtrl', ['$scope', 'Countries',
function($scope, Countries) {
$scope.title = 'Countries List';
$scope.countries = [];
$scope.status = '';
Countries.getList().then(
function(data, status, headers) { //success
$scope.countries = data;
},
function(data, status, headers) { //error
$scope.status = 'Unable to load data:';
}
);
}
]);
// controller of Country page
// Notice how we use $routeParams to grab the "id" of our country from the URL
// And use our service to look for the actual country by its ID.
myApp.controller('CountryCtrl', ['$scope', '$routeParams', 'Countries',
function($scope, $routeParams, Countries) {
$scope.country = {
id: '',
name: '',
abbrev: ''
};
var id = $routeParams.id;
Countries.getCountry(id).then(
function(data, status, hd) {
console.log(data);
$scope.country = data;
},
function(data, status, hd) {
console.log(data);
}
);
}
]);
In your "CountryCtrl", if you include $routeParams and use $routeParams.tlaname, you will have access to the tlaname. You can then use that to initialize your data.