I was given the following code to use to get the data I need, but it is not working for me. What am I doing wrong here. I have tried many things from the Angular.js docs and other stack overflow posts, but nothing has worked for me.
someurl
header: Content-Type = application/json
Pass in the following json:
{
"userID": "SomeUSER",
"password": "SomePSWD"
}
Below is the code I am using and it is not working.
function getGroup($scope, $http) {
$http.get('SOMEURL?callback=JSON_CALLBACK&userID=SomeUSER&password=SomePSWD ').
success(function(data) {
$scope.group = data;
});
}
this angularjs demo app show how to use http.jsonp
var httpJsonDemoController = angular.module('HttpJsonDemo', []);
httpJsonDemoController.controller('DataController', ['$scope', '$http', function($scope, $http) {
$http.jsonp("http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Waseem%20Hero").
success(function(data) {
$scope.data = data;
$scope.name = data.name;
$scope.salutation = data.salutation;
$scope.greeting = data.greeting;
}).
error(function (data) {
$scope.data = "Request failed";
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div id="wrapper" ng-app="HttpJsonDemo">
<div ng-controller="DataController">
<pre ng-model="data">
{{data}}
</pre>
<input ng-model='name' />
{{name}}
<input ng-model='salutation' />
{{salutation}}
<input ng-model='greeting' />
{{greeting}}
</div>
</div>
Related
I m currently really stuck on this topic.
I want to append the response data that I am retrieving from Express to my angular $scope and then redirect the user to their profile page.
My Controller Function looks like this:
$scope.login = function($event){
$event.stopPropagation();
$http({
method: 'POST',
url: '/login',
data: {
email: $scope.email,
password: $scope.password
}
}).success(function(data){
console.log(data.events)
$scope.events = data.events
$location.path('/profile');
}).error(function(err){
console.log(err)
})
Once I try to log in I get the logged data and then I'm redirected as desired. But my ng-repeat directive doesn't update.
JSON Output from my logged data:
[{
"type":"fussball",
"distance":"1",
"date":"Morgen",
"time":"10:30",
"maxAttendees":10,
"attendees:[
1345455466,
323232324,
454554534343,
898493839489,
892839283928,
283293283983]}
ng-repeat section:
<div ng-class="{'first': $first}" class="event-item"ng-repeat="event in events">
<div class="event-type {{event.type}}"></div>
<div class="event-seperator"></div>
<div class="event-body">
<div class="event-body-inner">
<span class="date"></span>
<p class="main">{{event.date}}</p>
<p class="sub">{{event.time}}</p>
</div>
<div class="event-body-inner">
<span class="attendees"></span>
<p class="main">{{event.attendees.length}}{{checkAttendees($index)}}</p>
<p class="sub">TEILNEHMER</p>
</div>
<div class="event-body-inner">
<span class="distance"></span>
<p class="main">{{event.distance}}</p>
<p class="sub">KM</p>
</div>
</div>
<div class="event-seperator"></div>
<div ng-click="selecEvent($event)" class="eventGo hvr-bounce-to-left">
<p>GO</p>
</div>
<div class="event-clicked">
<p>+ ZU DEINEN EVENTS HINZUGEFÜGT</p>
</div>
I'm actually not so familiar with asynch/synch programming so I hope someone can give me a hint ;) .
Thanks in advance!
You need to tell angular that there is an async update on the event list
}).success(function(data){
console.log(data.events)
$scope.events = data.events
$scope.$apply(); // <----- try to add this line
$location.path('/profile');
Maybe you would like to read:
When to use $scope.$apply()
and to watch:
Difference between $apply and $digest
The best way is to use a factory for this. I was about to write it but I found another question in another post.
Please up-vote the original poster if you like the comment.
https://stackoverflow.com/a/21855302/1549291
EDIT: Added plunker link for the implementation:
https://plnkr.co/edit/EimStRS1yMPbiU6PWKJN
(function () {
//factory
angular.module('app')
.factory('appFactory', ['$http', function ($http){
this.getlist = function(){
return $http.get('data.json')
.then(function(response) {
return response.data;
});
};
return this;
}]);
}());
angular.module('app').controller('appCtrl', ['$scope', '$http', '$log','$location', 'appFactory',
//controller
function($scope, $http, $log, $location, appFactory) {
// Chapters json data
appFactory.getlist()
.then(function(data) {
$scope.events = data;
});
}]);
I want to use multiple service in same controller. I can achieve with different service as mentioned below but it performs only one service
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<H1>Random Text is:</H1>
<div>{{myRandom}}</div>
<p>MuyLocation:: {{myLocation}}.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $location) {
$http.get("http://www.randomtext.me/api/").then(function (response) {
$scope.myRandom = response.data.text_out;
$scope.myLocation= $location.absUrl();
});
});
</script>
</body>
</html>
BUT, i want to use both service in same controller as mentioned below
app.controller('myCtrl', function($scope, $http, $location) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
$scope.myUrl = $location.absUrl();
});
});
So How can we perform both services in same controller.
Thanks in advance.
I think you can solved your problem with promise chaining.
$http.get("http://www.randomtext.me/api/").then(function success(response) {
return $q.resolve(response);
}, function error() {
return $http.get("welcome.htm");
}).then(function success(response) {
$scope.myWelcome = response.data;
$scope.myUrl = $location.absUrl();
});
If call to randomapi failed, so fetch welcome.html.
I am new to AngularJS and I'm trying to work with Angular dependency injections which involve the use of $http service. I have a .json file in the same directory as my html file and I am referring to that file in my controller. However, for some reason, the view does not change to reveal my data. What am I doing wrong? I get an error alert every time, but I don't get what I'm doing wrong. Any help would be appreciated.
index.html
<body ng-app="family" ng-controller="famctrl">
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
Search: <input ng-model="query">
</div>
<div class="col-md-10"><br>
Sort by:
<select ng-model="order">
<option value="name">Alphabetical</option>
<option value="age">Age</option>
</select>
<ul>
<li ng-repeat="sword in swords | filter:query| orderBy:order"><span>{{sword.name}}</span>
<p>{{sword.quanity}}</p>
<p>{{sword.price}}</p>
</li>
</ul>
<p>Total number of swords: {{swords.length}}</p>
</div>
</div>
</div>
family.js
var family = angular.module('family', []);
family.controller('famctrl', function($scope, $http) {
$http.get('records.json').success(function(data){
$scope.swords=data;
}).
error(function(data){
alert('error');
});
$scope.order="name";
});
records.json has the following format:
[
{
"name": "...",
"quantity": "...",
"price": "..."
},...
]
Maybe try this!
family.controller('famctrl', ['$scope', '$http', function($scope, $http) {
$http.get('records.json').success(function(data){
$scope.swords=data;
}).
error(function(data){
alert('error');
});
$scope.order="name";
}]);
You must define like that:
'$scope', '$http' are load controller scope and http
family.controller('famctrl', ['$scope', '$http', function($scope, $http) {
$http.get('records.json').success(function(data){
$scope.swords=data;
}).
error(function(data){
alert('error');
});
$scope.order="name";
}]);
So, this is my HTML.
<input type="text" id="ghusername" ng-model="username" placeholder="Github username...">
<span id="ghsubmitbtn" ng-click="getUsers()">Pull User Data</span>
This is my Controller A.
app.controller("homeController", ["$scope", "$http", function ($scope, $http) {
$scope.getUsers = function () {
$http.get("https://api.github.com/users/" + $scope.username)
.success(function (data) {
//some stuff
})
And this is B (for posting sake). How do I get this username on the HTML ngModel, so that I can show it in another controller? ex:
app.controller("reposController", ["$scope", "$http", function ($scope, $http) {
$scope.getRepos = function () {
$http.get("https://api.github.com/users/" + $scope.username + "/repos")
.success(function (data) {
// some stuff
})
};
I've tried to user services, factories and even $rootScopes, but they just don't seem to work, any help? Btw, if I wasn't clear tell me and I will edit the post, Thank you.
EDIT: I ended up using $rootScope, I know it isn't the best idea but it was a minor thing. I'll keep all your answers for reference tho, as I'm sure they all work but I'm just too dumb to implement them.. Thank you.
You must to refernce $rootScope into your controllers:
app.controller("homeController", ["$scope", "$http","$rootScope", function ($scope, $http, $rootScope) ...
and after that just access rootscope variables:
controller1: $rootScope.someValue = "some value";
Controller2: $scope.controllerScopeValue = $rootScope.someValue;
Use service
app.service('name', [function(){}])
Then add 'name' to both the controllers like
app.controller("reposController", ["$scope", "$http", 'name', function ($scope, $http, name) {
$scope.name = name;
Then you can access it like
name.username
and in html
<input type="text" id="ghusername" ng-model="name.username" placeholder="Github username...">
Try something like this
http://jsfiddle.net/devkickstart/nevyhdn0/2/
Using a factory you can share the data between controller like so...
<div ng-app="myApp">
<div data-ng-controller="reposCtrl">
<input type="text" id="ghusername" ng-model="username" placeholder="Github username..." ng-init="getRepos()" />
{{data}}
</div>
<div data-ng-controller="homeCtrl"> <span id="ghsubmitbtn" ng-click="getUsers()">Pull User Data</span>
{{otherData}}
</div>
</div>
angular.module("myApp", [])
.factory("dataFact", ["$rootScope", function ($rootScope) {
var myData = "value from factory";
return {
getData: function () {
return myData;
},
setData: function (newVal) {
this.myData = newVal;
}
}
}]).controller("homeCtrl", ["$scope", "dataFact", function ($scope, dataFact) {
$scope.getUsers = function () {
$scope.otherData = dataFact.getData();
}
}]).controller("reposCtrl", ["$scope", "dataFact", function ($scope, dataFact) {
$scope.getRepos = function () {
$scope.username = dataFact.getData();
}
}]);
With some assumptions about your data model, this should work.
It creates a shared singleton object. One controller adds the user (or whatever data) as an attribute of that. Then other controllers, or indeed the same controller if it is reloaded, can then access the same data on shared.
Note here that a service just returns a singleton of anything, it doesn't need code or methods. In this case, it's easier to use a value instead which is shorthand for function() { return {}; } and works just as well.
Remember to inject shared wherever it is needed.
app.controller("homeController", ["$scope", "$http", "shared", function ($scope, $http, shared) {
$scope.getUsers = function () {
$http.get("https://api.github.com/users/" + $scope.username)
.success(function (data) {
shared.user = data.user; // or wherever it comes from
//some stuff
})
app.controller("reposController", ["$scope", "$http", "shared", function ($scope, $http, shared) {
$scope.getRepos = function () {
$http.get("https://api.github.com/users/" + shared.user.name + "/repos")
.success(function (data) {
// some stuff
})
};
app.value('shared', {});
My setup is NodeJS, MongoDB, and Angular. I'm currently trying to add POSTing capability to my test code but can't quite wrap my head around it. Currently I can pull data from the DB and I threw together a quick and dirty form/factory based on a number of examples I've seen to try to get the POST function working.
The problem I'm running into is actually getting the values to be added to the DB. When I submit the form, a new ObjectID is created in the DB with a "_v" field and a value of 0. So I know the POST is at least being sent to the DB, but the values I want are not. I'm sure I'm doing something stupid and any help is greatly appreciated.
Here is my controller/factory setup: (I named the POST factory "taco" so it would stand out. Also because they're delicious.)
angular.module('app', ['ngRoute'])
.factory('Users', ['$http', function($http) {
return $http.get('/users');
}])
.factory('taco', ['$http', function($http) {
return $http.post('/users');
}])
.controller('UserController', ['$scope', 'Users', function($scope, Users) {
Users.success(function(data) {
$scope.users = data;
}).error(function(data, error) {
console.log(error);
$scope.users = [];
});
}])
.controller('ExampleController', ['$scope', 'taco', function($scope, taco) {
$scope.submit = function() {
if ($scope.users.name) {
$scope.name.post(this.name);
$scope.name = '';
}
};
}]);
Here is my form:
<div>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter the things:<br/>
<input type="text" ng-model="name" name="user.name" placeholder="name" /><br/>
<input type="text" ng-model="emp_id" name="user.emp_id" placeholder="EID" /><br/>
<input type="text" ng-model="loc" name="user.loc" placeholder="location" /><br/>
<input type="submit" id="submit" value="Submit" />
</form>
</div>
To post using the $http service you can do:
angular.module('myApp')
.controller('MyController', function($scope, $http) {
$http.post('/destination', {my: 'data'});
});
You're not sending any data in your POST request. The taco service just executes a $http.post call and returns the promise.
Please look at the $http service documents: https://docs.angularjs.org/api/ng/service/$http
I would define a function submit that would send the data once a user clicks on submit:
$scope.submit = function() {
$http.post('/destination', {my: 'data'});
}