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>
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'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;
});
});
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>
So I keep getting this ReferenceError: $http is not defined, even though I have included $http in the controller, which seems to be the most common cause of this error message. I've tried also passing $http into the function itself, but that doesn't solve it.
I feel like I am missing something SUPER obvious, so any help would be much appreciated, thank you!
I've included the entire script, just for clarity's sake. You can see the post request towards the end of the script, inside the finaliseDay function.
Thanks!
Here is the error:
ReferenceError: $http is not defined
at l.$scope.finaliseDay (http://localhost:8888/goalzy.js:69:12)
at ib.functionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:198:303)
at Dc.(anonymous function).compile.d.on.f (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:214:485)
at l.$get.l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:125:305)
at l.$get.l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:6)
at HTMLAnchorElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
at HTMLAnchorElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)angular.js:11607 (anonymous function)angular.js:8557 $getangular.js:14502 $get.l.$applyangular.js:21440 (anonymous function)angular.js:3014 c
Here is the HTML first
<!doctype html>
<html ng-app="goalzy">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
<script src="goalzy.js"></script>
</head>
<body>
<div class="container">
<div class="well">
<h2>Goalzy</h2>
Dev TODO
<ul>
<li>Hook up the API to persist data</li>
</ul>
<div ng-controller="TodoController">
<span>{{remaining()}} of {{todos.length}} remaining today</span>
<span>You're at {{percentComplete()}}% completion</span>
[ finalise day ]
<ul class="unstyled">
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
<form ng-submit="addTodo()">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
<hr>
<div class="historial" ng-repeat="h in historicalDailyPercentages">
<ul>
<li>Date: {{h.date}}</li>
<li>Percentage of Daily Tasks Completed: {{h.percent}}%</li>
<li><div>Tweet it!</div></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
And here is the JS:
//Goalzy.js
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.todos = [];
$scope.historicalDailyPercentages = [];
$scope.addTodo = function() {
if ($scope.todoText != "") {
if ($scope.todos.length < 3) {
$scope.todos.push({text:$scope.todoText, done:false});
$scope.todoText = '';
//Save to DB
}
else {
alert("You can only have 3 todos per day!");
$scope.todoText = '';
}
} else {
alert("you must write something");
}
};
$scope.remaining = function() {
var count = 0;
angular.forEach($scope.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.percentComplete = function() {
var countCompleted = 0;
angular.forEach($scope.todos, function(todo) {
countCompleted += todo.done ? 1 : 0; //Simply calculates how many tasks have been completed
console.log(countCompleted);
});
var totalCount = $scope.todos.length;
var percentComplete = countCompleted / totalCount * 100;
return percentComplete;
}
$scope.finaliseDay = function(percentComplete) {
alert("You're finalising this day with a percentage of: " + percentComplete);
var today = new Date();
var alreadyPresent = $scope.historicalDailyPercentages.some(function (item) {
return item.date.getFullYear() === today.getFullYear() &&
item.date.getMonth() === today.getMonth() &&
item.date.getDate() === today.getDate();
});
//Confirm that nothing has alreayd been posted for today
if (!alreadyPresent) {
$scope.historicalDailyPercentages.push({
percent: percentComplete,
date: today
});
// Simple POST request example (passing data) :
$http.post('/api/postDailyPercentage.php', {msg:'hello word!'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("data" + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("data" + data);
});
}
else {
alert("You're all set for today - see you tomorrow!");
}
console.log($scope.historicalDailyPercentages);
}
}]);
Provider won't be available inside controller with suffix 'Provider', you can do access them by provider name only here it would be $http only, also remove ;
after config initialization
$httpProvider setting should be done inside the angular config phase
CODE
angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
}]);
.controller('TodoController', ['$scope', '$http', function($scope, $http) {
//controller code here
}]);
Note: For sure you should remove $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8'; line from controller
Working Plunkr
You don't have to use "$httpProvider" in controller, use $http instead.
e.g.
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
As best practice, do not configure provider ($http) in controller. Do it in config section. as below
var app = angular.module('goalzy', []);
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
});
app.controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.title="scope title";
//$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);
see working plunk at http://run.plnkr.co/plunks/4mY4izqc48P8wVQFumZ8/ with your html.
I watched a video on lynda, but unfortunately it's not on the latest version of the API.
The video shows how to use firebaseSimpleLogin, but this was changed to authWithPassword if I want a email & password type of authentication.
I can login, logout and register but the
PROBLEM is: I can't verify if the user is logged in or logged out.
here is my code below:
The Factory
GlobalCtrl.factory('Auth', ['$firebaseAuth', function($firebaseAuth){
var ref = new Firebase("https://taxiq-app.firebaseio.com"); //call on firebase database
//var objects = $firebase(ref) // reference database
return $firebaseAuth(ref);
}]);
The controller
taxiGlobalCtrl.controller('LoginController',['$scope','$firebase','Auth' ,'$location', function($scope, $firebase,Auth, $location){
$scope.login = function(){
Auth.$onAuth(function(authData) {
$scope.authData = authData;
console.log($scope.authData);
});
Auth.$authWithPassword({
email: $scope.username,
password: $scope.password
}).then(function(authData) {
console.log("Logged in as:", authData.uid);
$location.path('/tickets');
}).catch(function(error) {
console.error("Authentication failed:", error);
$scope.loginError = "loging error";
});
}
}]);
The naV that will show logout after logged in
<div>
<a class="navbar-brand" ng-href="#">Tiketa</a>
<ul class="nav navbar-nav">
<li ng-hide="authData"><a ng-href="#/login">Login</a></li>
<li ng-hide="authData"><a ng-href="#/register">Register</a></li>
<li ng-show="authData"><a ng-href="#/tickets">Tickets</a></li>
<li ng-show="authData"><a ng-href="#" ng-click="auth.$unauth()">logout</a></li>
</ul>
note: I'm fresh from online resources about angular and firebase,... I'm a noob