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";
}]);
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 have a simple angularjs application, in which I want to run a slider and the slider elements come from $http request.
Here is the code for reference:
var mainApp = angular.module("myapp", []);
mainApp.run(['$rootScope', '$http',
function($rootScope, $http) {
$http.post('process.php?ajax_type=getChild').success(function(data) {
if (data.success) {
console.log(data.child); // data received...
$rootScope.categories = data.child;
}
});
}]);
mainApp.controller('gridChildController', function($scope, $http, $rootScope) {
console.log($rootScope.categories); // this is also null....
$scope.brands = $rootScope.categories;
$scope.finished = function(){
jQuery('.brand_slider').iosSlider({
desktopClickDrag: true,
snapToChildren: true,
infiniteSlider: false,
navNextSelector: '.brands-next',
navPrevSelector: '.brands-prev',
lastSlideOffset: 3,
onSlideChange: function (args) {
}
});
};
});
Here is code of the template file:
<div ng-app="myapp">
<div ng-controller="gridChildController" class="brand_slider" >
<div class='slider'>
<div class="slide col-md-5ths col-sm-4 col-xs-12 text-center" ng-repeat="x in brands" ng-init="$last && finished()">
<img class="img-responsive center-block" ng-src="{{x.image}}" title="{{x.title}}" alt="{{x.title}}">
</div>
</div>
</div>
</div>
When I run this code, I get the data from the $http but ng-repeat doesn't work, and in the controller I get data null.
If you put something on $rootScope it will be also available on the child scopes. So you can bind straight to categories (no need to copy it to $scope.brands):
ng-repeat="x in categories"
I have used a controller in order to use an api which works fine but I want to use it using factory or service and have tried this so many times but may be I don't have that much understanding of it. I am currently taking a course for AngularJs, so I am sorry if I am asking something stupid.
Also it would be great anyone can tell me that what would be best to use factory or service or something else.
This way it works fine:
HTML:
<div ng-controller="PromiseCtrl">
<li ng-repeat="post in posts" >
{{post.link}}<br/>
{{post.title}}
</li>
</div>
Controller:
.controller('PromiseCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
$scope.posts = value.data;
});
}]);
This is where I am facing problem:
HTML:
<div ng-controller="PromiseCtrl">
<li ng-repeat="post in posts" >
{{post.link}}<br/>
{{post.title}}
</li>
</div>
Controller:
.controller('PromiseCtrl', ['$scope', '$http', function($scope, $http) {
$http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
$scope.posts = value.data;
});
}])
Factory:(I am not using this correctly, I think)
angular.module('confusionApp')
.factory('menuFactory', function() {
$http.get('http://www.zemtv.com/wp-json/wp/v2/posts').then(function(value) {
var posts = value.data;
});
});
I haven't tested any of this but it's along the lines of:
angular.module('confusionApp')
.factory('menuFactory', function() {
return {
getPosts: function () {
return $http.get('http://www.zemtv.com/wp-json/wp/v2/posts')
}
}
});
Then from the controller:
.controller('PromiseCtrl', ['$scope', '$http', 'menuFactory', function($scope, $http, menuFactory) {
menuFactory.getPosts().then(function(response){
$scope.posts = response.data;
});
}]);
It would be good to read what up more on the uses of services and how they are injected and used by controllers.
I'm studying AngularJS Services and I'm having a problem.
That's my Angular code:
var app = angular.module("todoListApp");
app.controller('MainController', MainController);
MainController.$inject = ['$scope'];
function MainController($scope, dataService){
$scope.helloConsole = dataService.helloConsole;
};
app.service('dataService', function(){
this.helloConsole = function(){
console.log("console services");
};
});
That's my HTML Code
<div ng-controller="MainController" class="list">
<div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
<div class="actions">
Edit
Save
Delete
</div>
</div>
</div>
I'm trying to make it so that when I click on Save, the console shows me "console services", but it's giving me an error:
angular.js:13424 TypeError: Cannot read property 'helloConsole' of undefined
Proper Angular Structure
you need to change the way you have written your code. It should look more like this
angular.module("todoListApp", [])
.controller('MainController', ['$scope', 'dataService', function($scope, dataService){
$scope.helloConsole = dataService.helloConsole;
}])
.service('dataService', [function(){
this.helloConsole = function(){
console.log("console services");
};
}]);
Also this is a 'data service' is this gettig data with a http call? Because if so then make a factory.
Controllers for business logic
Factories for data requests
Services for things like login
Directives for DOM manipulation
Filters for format
Return a singleton service object from angular.service's second function argument. Also, if you're explicit about the dependencies of your controller, thinks will work a lot clearer/better:
var app = angular.module("todoListApp", []);
app.controller('MainController', ['$scope', 'dataService', MainController]);
function MainController($scope, dataService){
$scope.helloConsole = dataService.helloConsole;
$scope.todos = [{txt:"todo 1"}, {txt:"todo 2"}];
}
app.service('dataService', function(){
return {
helloConsole: function(){
console.log("console services");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.js"></script>
<div ng-app="todoListApp">
<div ng-controller="MainController" class="list">
<div class="item" ng-class="{'editing-item' : editing, 'edited': todo.edited}" ng-repeat="todo in todos">
{{todo.txt}}
<div class="actions">
Edit
Save
Delete
</div>
</div>
</div>
</div>
I rewrote this a little bit so it's easier to understand (for me at least).
I have added a "todos" array to your code just to make the ng-repeat fire.
var app = angular.module("todoListApp",[])
.service('dataService', function(){
this.helloConsole = function(){
console.log("console services");
};
})
.controller('MainController', [ '$scope', 'dataService',function ($scope,dataService) {
$scope.helloConsole = dataService.helloConsole;
$scope.todos = [ {
"todo":"1"
}
]
}])
;
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>