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;
});
}]);
Related
I have a parent controller with some children controllers, and I want them all to share the same data that I retrieve from an Api service.
Controllers:
var app = angular.module('mymodule',[]);
app.controller('main', ['$scope', 'Api', function($scope, Api) {
var getList1 = Api.getList1()
.then(function(resp) {
$scope.list1 = resp.data;
});
var getList2 = Api.getList2()
.then(function(resp) {
$scope.list2 = resp.data;
});
}]);
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = ?
$scope.list2 = ?
}]);
app.controller('child2', ['$scope', function($scope) {
$scope.list1 = ?
}]);
View:
<div ng-controller="main">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
<ul>
<li ng-repeat="list in list2">
{{list.item}}
</li>
</ul>
</div>
<div ng-controller="child1">
<ul>
<li ng-repeat="list in list1">
{{list.item}}
</li>
</ul>
</div>
</div>
I tried to use this solution with Angular’s events mechanism ($on, $emit).
The problem was that I had to figure out which child controller is active and send the data when the promise has resolved. It ends with ugly spaghetti code...
Well, the best way is to use a service to have your API handling atomar placed inside your application. This fiddle shows you how you could achieve what you try to. By using AngularJS services you will be able to share the same data, objects and functions between controllers and let them interact with eachother. This is undepending on the amount of your controllers inside your application.
The following example is a full working API service with real HTTP-Requests and a real AngularJS service handling. It will help you by implement such logic inside your application. Please dont forget to check out the fiddle demo.
View
<div ng-controller="MyCtrl">
<h1>
MyCtrl
</h1>
<button ng-click="clearData()">
Clear data by using MyCtrl
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
<br /><br />
<div ng-controller="MyOtherCtrl">
<h1>
MyOtherController
</h1>
<button ng-click="clearData()">
Clear data by using MyOtherController
</button>
<div ng-repeat="user in users">
<p>
Username: {{ user.name }}
</p>
</div>
</div>
AngularJS Application
var myApp = angular.module('myApp',[]);;
myApp.controller('MyCtrl', function ($scope, apiService) {
$scope.users = apiService.getResponseData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
});
myApp.controller('MyOtherCtrl', function ($scope, apiService) {
apiService.loadData();
$scope.$watch(function () { return apiService.getResponseData()}, function (newValue, oldValue) {
$scope.users = newValue
});
$scope.clearData = function () {
apiService.reset();
}
})
myApp.service('apiService', function ($http) {
var responseData = null;
return {
loadData: function () {
return $http({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET'
}).then(function (response) {
responseData = response.data
});
},
getResponseData: function () {
return responseData
},
reset: function () {
responseData = null;
}
}
});
As your data is in the scope of the parent controller, you can access it in children controllers with $scope.$parent:
app.controller('child1', ['$scope', function($scope) {
$scope.list1 = $scope.$parent.list1;
$scope.list2 = $scope.$parent.list2;
}]);
Write your children as directives, and then you can inject data on the scope.
yourModule.directive('child1', function() {
return {
scope: {list1:'=',
controller: function (scope) {
//not sure you even need a controller, but it might look like this
scope.doSomething = function() {
//access scope.list1 here
}
},
template: '<ul><li ng-repeat="list in list1">{{list.item}}<li><ul>'
}
}
Usage:
<child1 list1="list1"></child1>
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"
}
]
}])
;
Recently, I began to study Angular. So much I do not know. I'm trying to get json data from a php file to use within an Angular controller. But the data from php file does not exceed.
controllers.js:
app.controller('MainCtrl',['$scope', '$resource', '$http',
function($scope, $resource,$http) {
$http.get('/xbmc.php').success(function(data) {
$scope.data = data;
});
}]);
xbmc.php:
<?
include('sys/inc/config.inc.php');
include(SMARTY_DIR.'Smarty.class.php');
include(BASE_DIR .'sys/inc/classes.inc.php');
include(BASE_DIR .'sys/inc/init.inc.php');
include(BASE_DIR .'xbmcApi.php');
$jsonData = new xbmcApi($_GET['action']);
/**
if (MEGAKINO_LOGED)
{
**/
$json = $jsonData->getResult();
/**
}
else
$json = array('authStatus' => '0');
**/
echo json_encode($json);
?>
index.html:
<body ng-controller="MainCtrl">
<div class="wrapper">
<h2>{{title}}</h2>
<div class="row">
<div class="col-md-1 col-sm-2 col-xs-4" style="margin-top: 0.5%;" ng-repeat="item in data.items">
<div class="image" style="margin-bottom: 1%">
<a data-ng-href="#!/seasons/serie/{{item.id}}">
<img data-ng-src="/files/series/thumb-{{item.id}}.jpg" alt=""/>
</a>
</div>
<div class="info">
<a data-ng-href="#!/seasons/serie/{{item.id}}">
<b>{{item}}</b>
<u>Рейтинг: {{item.rate}}</u>
</a>
</div>
</div>
</div>
</div>
</body>
Your php code tells that your json will be build if a $_GET['action'] param is passed:
$jsonData = new xbmcApi($_GET['action']);
Yet, you are not passing any data as a query string from your angular controller. Try something like:
app.controller('MainCtrl',['$scope', '$resource', '$http',
function($scope, $resource,$http) {
$http({
url: '/xbmc.php',
method: "GET",
params: {action: 'some_action'}
}).success(function(data) {
$scope.data = data;
});
}]);
AS #CharlieH said, check for errors on your console:
app.controller('MainCtrl',['$scope', '$resource', '$http',
function($scope, $resource,$http) {
$http.get('/xbmc.php')
.then(function(response) {
$scope.data = response.data;
})
.catch (function(error) {
//check for errors here
console.log(error);
throw error;
});
}]);
Also the .success method has been deprecated. We should all be migrating to using .then and .catch. For more information on that see: Deprecation of the .success and .error methods in the $http service
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>