I'm programming for a college assignment and I've got no idea what I did wrong, so looking for pointers here.
So I'm trying to access events from a database and display them as thumbnails. Where am I going wrong?
HTML Code:
<div class="col-sm-6 col-md-3" ng-repeat="event in EventCtrl.events" ng-controller="EventController as EventCtrl">
<div class="thumbnail tile tile-medium">
<a href="#" data-toggle="modal" data-target="#view-event-modal">
<img id = "eventImg" src="/img/sports.png" alt="Sports">
</a>
</div>
Angular Controller:
angular.module('EventCtrl', []).controller('EventController', function($http) {
$http.get("/events")
.then(function(response) {
this.events = {}
this.events = response.data;
});
});
Node function:
app.get('/events', function(req, res){
eventData = Event.find({}).toArray();
res.render('events', eventData);
});
Your controller should manipulate the $scope, and your view should interact with the scope.
Why don't try something like that
angular.module('EventCtrl', []).controller('EventController', function($scope, $http) {
$http.get("/events").then(function(response) {
$scope.events = response.data;
});
});
Related
Hi guys I had used this code my AngularJS app to execute a GET request, now I want to use it in Angular I have some problems with update it can anyone help me ?
script :
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("http://---:8080/api/v1/users")
.then(function(response) {
$scope.users = response.data;
$scope.AfficherMap = AfficherMap;
console.log(response.data);
}).catch(function(response) {
console.log("ERROR:", response);
});
html:
<div ng-controller="myCtrl" style="width: 250px;">
<div ng-repeat="user in users" ng-click="AfficherMap(user.id)">
<a>{{user.id}} {{user.firstName}} {{user.lastName}}</a>
</div>
</div>
You can do this in this way...
Make a get function in UserService:
constructor(http:HttpClient){}
getUsers(){
return this.http.get("api_url");
}
Now In your component call this function.
constructor(private userService: UserService){
}
ngOninit(){
this.userService.getUsers().subscribe((res)=>{
console.log(res); // This is your users list...
this.users = res;
});
}
Now In your html
<div style="width: 250px;">
<div *ngFor="let user of users">
<a (click)="AfficherMap(user.id)">{{user.id}} {{user.firstName}-
{{user.lastName}}
</a>
</div>
</div>
AngularJS(1.x) and Angular(2+) are totally different frameworks, in Angular(2+) you will need to use HttpClient module to do an HTTP call more details on the official doc
Find a suggestion for your code:
getUsers() {
this.api.getUsersCall()
.subscribe(users => {
for (const u of (users as any)) {
this.users.push({
name: u.name,
username: u.username
});
}
});
}
given that api is an instance of the APIService you need to create a module for it and declare it in your component class with the specifier private, APIService module will contains the definition of getUsersCall:
getUsersCall() {
return this.http.get("http://---:8080/api/v1/users");
}
I am working with Ionic and the api of The Movie Database. I wrote a service to make my http request which comes back all good. I get all my outputs in the console.log but for some reason I am still not able to show the data in the view. So I was wondering if I am doing it wrong when it comes to 2 way databinding
Code of my service:
angular.module('starter.services', [])
.service('HotMoviesService', function($http, $q){
var final_url = "https://api.themoviedb.org/3/movie/popular?api_key=XXXX";
var self = {
'hotMovies' : [],
'loadHotMovies' : function() {
var d = $q.defer();
$http.get(final_url)
.success(function success (data){
console.log(data);
self.hotMovies = data.results;
d.resolve('The promise has been fulfilled');
})
.error(function error (msg){
console.error("There was an error retrieving the data " , msg);
d.reject("The promise was not fulfilled");
});
return d.promise;
}
};
return self;
});
My controller.js code:
angular.module('starter.controllers', ['ionic.contrib.ui.hscrollcards', 'starter.services'])
.controller('StartCtrl', function($scope, $http, HotMoviesService) {
$scope.hotmovies = [];
HotMoviesService.loadHotMovies().then(function success (data){
console.log(data);
$scope.hotmovies = HotMoviesService.hotmovies;
},
function error (data){
console.log(data)
});
})
My html code:
<ion-view view-title="The Movie Bank">
<ion-content class="background">
<h1 class="padding titleStart">Welcome to The Movie Bank</h1>
<div class="logo"></div>
<!-- HOT -->
<a class="customHref" href="#/app/hot">
<h1 class="padding customH1">Hot</h1>
</a>
<hscroller>
<ion-scroll direction="x" scrollbar-x="false">
<hcard ng-repeat="hotmovie in hotmovies">
<a href="#/app/hot/{{hotmovie.id}}">
<img ng-src="http://image.tmdb.org/t/p/w92/{{hotmovie.poster_path}}" >
</a>
</hcard>
</ion-scroll>
</hscroller>
</ion-content>
</ion-view>
Here is a screenshot of my console, as you can see everything works fine:
You need hotMovies, note the "m" case:
$scope.hotmovies = HotMoviesService.hotMovies;
I'm getting some problem getting the results from my api server with angularjs.
This is my code:
home.html (view)
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ message }}</p>
Orders!
</div>
<ul>
<li ng-repeat="order in orders">{{order}}</li>
</ul>
main.js (controller)
app.controller('mainController', function($scope, $http) {
$scope.message = 'Everyone come and see how good I look!';
$scope.orders = [];
$scope.getOrders = function(){
$http.get('http://apidemo.dev/api/orders').success(function(response){
console.log("My data: " + response);
$scope.orders = response;
});
}
});
When I click the button, I can see the results in the console, but not in the list.
If use this code in the controller, it works when it loads, and when I click the button:
app.controller('mainController', function($scope, $http) {
$scope.message = 'Everyone come and see how good I look!';
$http.get('http://apidemo.dev/api/orders').success(function(response){
console.log("My data: " + response);
$scope.orders = response;
});
$scope.getOrders = function(){
$http.get('http://apidemo.dev/api/orders').success(function(response){
console.log("My data: " + response);
$scope.orders = response;
});
}
});
What is the problem ?
Thanks!
Seems like you were using ngRoute and you have href="#" in your anchor, which leads you redirection to blank page, Keep href="" will help you in css to show pointer: cursor; on hover of it
Button
Orders!
Thanks everybody for your help.
The problem was the link in the view...
Orders!
would be:
<a ng-click="getOrders()">Orders!</a>
I created one angular JS application using MVC 4
where i created one view which renders templates in that we have one template which contains large amount of data as one lack records for that i am looking to implement Infinite Scrolling
1.index.cshtml
<div id="sidebar-left" class="span2">
<div class="nav-collapse sidebar-nav">
<ul class="nav nav-tabs nav-stacked main-menu">
<li class="navbar-brand">Talks</li>
<li class="navbar-brand">SRDNames</li>
<li class="navbar-brand">Speakers</li>
<li class="navbar-brand">Add Talk</li>
</ul>
</div>
</div>
SRDNames.cshtml
<div class="box-content">
<table class="table table-striped table-bordered bootstrap-datatable datatable">
<tr>
<th>
SRD_NAME
</th>
<th>
CREATED_BY_USER_ID
</th>
</tr>
<tr ng-repeat="srdname in srdnames">
<td>
{{srdname.sRD_NAME}}
</td>
<td>
{{srdname.cREATED_BY_USER_ID}}
</td>
</tr>
</table>
3.eventModule.js
var eventModule = angular.module("eventModule", []).config(function ($routeProvider, $locationProvider) {
//Path - it should be same as href link
$routeProvider.when('/Events/Talks', { templateUrl: '/Templates/Talk.html', controller: 'eventController' });
$routeProvider.when('/Events/Speakers', { templateUrl: '/Templates/Speaker.html', controller: 'speakerController' });
$routeProvider.when('/Events/AddTalk', { templateUrl: '/Templates/AddTalk.html', controller: 'talkController' });
$routeProvider.when('/Events/SRDNames', { templateUrl: '/Templates/SRDNames.html', controller: 'srdnamescontroller' });
$locationProvider.html5Mode(true);
});
srdnamescontroller.js
eventModule.controller("srdnamescontroller", function ($scope, EventsService) {
EventsService.getSRDName().then(function (srdnames) { $scope.srdnames = srdnames }, function ()
{ alert('error while fetching talks from server') })
});
5.EventsService.js
eventModule.factory("EventsService", function ($http, $q) {
return {
getSRDName: function () {
// Get the deferred object
var deferred = $q.defer();
// Initiates the AJAX call
$http({ method: 'GET', url: '/events/GetSRDName' }).success(deferred.resolve).error(deferred.reject);
// Returns the promise - Contains result once request completes
return deferred.promise;
},
});
looking to implement like http://jsfiddle.net/vojtajina/U7Bz9/ in above application.. please help
Demo
There are many possible solutions. Here is one that may work for you.
Implement a scroll module that defines the following:
An infiniteScroll directive
A data service to get the scrollable data
You can use the scroll module from within your app:
HTML:
<div ng-app="app" ng-controller="ctrl">
<div infinite-scroll="items">
</div>
</div>
JS:
var app = angular.module('app', ['scroll']);
app.controller('ctrl', function($scope, dataService) {
$scope.items = [];
dataService.loadMore($scope.items, function(lastItem) {
var items = [];
var id = lastItem ? lastItem.id : 0;
for (var i = 0; i < 5; i++) {
items.push({id: id + i});
}
return items;
});
});
The dataService exposes a loadMore method that accepts an array, and a callback function to load more data. The above example loads more data by looping through 5 items, and adding to the array. But you can customize this function callback to retrieve data from another service:
var app = angular.module('app', ['scroll']);
app.controller('ctrl', function($scope, $http, dataService) {
$scope.items = [];
dataService.loadMore($scope.items, function(lastItem, done) {
var lastItemId = lastItem ? lastItem.id : '';
$http({ method: 'GET',url:'api/items/' + lastItemId})
.success(function(items) {
done(items);
});
});
});
Hi I'm just learning angular, and I was wondering if someone could let me know what I'm doing wrong with setting up this simple load bar in the Yeoman signup page
In the signup.controller.js, I have the following code:
'use strict';
angular.module('lolBetApp')
.controller('SignupCtrl', function ($scope, $http, Auth, $location) {
$scope.user = {};
$scope.errors = {};
$scope.register = function(form) {
$scope.submitted = true;
if(form.$valid) {
Auth.createUser({
summonerName: $scope.user.summonerName,
email: $scope.user.email,
password: $scope.user.password
})
.then( function() {
// Account created, redirect to home
$location.path('/');
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
};
$scope.$emit('LOAD')
$http.jsonp('http://filltext.com/?rows=10&delay=5&fname={firstName}&callback=JSON_CALLBACK')
.success(function(data){
$scope.people=data;
$scope.$emit('UNLOAD')
});
}).
controller('loaderController',['$scope',function($scope){
$scope.$on('LOAD',function(){$scope.loading=true});
$scope.$on('UNLOAD',function(){$scope.loading=false });
}]);
And in my signup.html, I have the following code:
<div ng-controller="loaderController">
<div class="alert alert-info" ng-show="loading">Summoning...</div>
<div ng-controller="myController">
<ul>
<li ng-repeat="person in people">
{{person.fname}}
</li>
</ul>
</div>
I was able to get this to work easily without using Yeoman, using the code in this link http://plnkr.co/edit/30qbDj0xuBESp6LT8etM?p=info
Does anyone know what I'm doing wrong?
Thanks,
Nevermind! I just got it to work. The problem is that I had the wrong name for the controller in the signup.html page
<div ng-controller="SignupCtrl">
<ul>
<li ng-repeat="person in people">
{{person.fname}}
</li>
</ul>
</div>