I need to update view when new data created at server?
How to do this correct?
My controller
app.controller('MainController', ['$scope', 'games', function($scope, games) {
games.success(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
}]);
My factory
app.factory('games', ['$http', function($http) {
return $http.get('./game')
.success(function(data) {
return data;
})
.error(function(data) {
return data;
});
}]);
Remember that services in Angular are objects. So create a simple method that returns a promise, to manage it in the controller.
Controller
app.controller('MainController', ['$scope', 'games', function($scope, games) {
games.get().then(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
}]);
Service
app.service('games', ['$http', function($http) {
this.get = function() {
return $http.get('./game');
};
}]);
you can use $timeout if you do not wish to use websockets
$timeout(function(){
games.success(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
},1000);
Update : sorry it should be $interval
$interval(function(){
games.success(function(data) {
console.log(data[0]);
$scope.games = data[0];
});
},1000);
Update : how to do this using factory
app.factory('games', ['$http', function($http) {
return {
getGame: function() {
return $http.get('./game');
}
}
}]);
Now in your controller
app.controller('MainController', ['$scope', 'games', function($scope, games) {
games.getGame().success(function(data) {
$scope.games = data[0];
});
}]);
Related
Im creating a custom service, where it is working, is returning me in the function service the data, the problem is when i call it in the controller, it is returning me 'undefined'.
Service:
var toDoListServices = angular.module('toDoListServices', []);
toDoListServices.factory('DataTasksService', function($http){
return {
getTasks: function(){
$http.get('js/data.json').success(function(data){
return data;
})
}
}
});
Controllers:
var toDoListController = angular.module('toDoListController', []);
toDoListController.controller('ListController', ['$scope', 'DataTasksService', function($scope, DataTasksService){
$scope.tasks = DataTasksService.getTasks();
}]);
App.js:
var myApp = angular.module('myApp', [
'ngRoute',
'toDoListController',
'toDoListServices'
]);
getTasks doesn't return anything. A return inside success does nothing.
You need to return the $http promise.
Try
toDoListServices.factory('DataTasksService', function($http){
return {
getTasks: function(){
// return the promise
return $http.get('js/data.json');
}
}
});
In controller:
DataTasksService.getTasks().then(function(response){
$scope.tasks = response.data;
});
So far this is the complete source
angular
.module('app')
.factory('Friends', ['$http',function($http){
return {
get: function(){
return $http.get('api/friends.json')
.then(function(response){
alert(JSON.stringify( response.data));
return response.data;
});
}
};
}])
Controller:
angular.module("app")
.controller('homeCtrl',['$scope','Friends',
function($scope, Friends){
$scope.title = "Welcome";
$scope.items=["2016","2015", "2014"];
$scope.friends = Friends.get();
$scope.save = function(){
$http.post('/api/friends', friends);
}
}])
$stateProvider
.state('home',{
url:'/',
templateUrl:'templates/home.html',
controller: 'homeCtrl',
resolve : {
friends:['Friends', function(Friends){
return Friends.get();
}]
}
})
The result when I try to alert it:
The UI Blank:
*and my nav bar ddl is not working how to do the trick?
Friends.get() return a promise. You must use the then method :
Friends.get().then(function(data) { $scope.friends = data; }); //instead of $scope.friends = Friends.get();
you should use $q for promises:
angular
.module('app')
.factory('Friends', ['$http', '$q' ,function($http, $q){
var self = {};
self.get = function() {
var deferred = $q.defer();
$http.get('api/friends.json')
.success(deferred.resolve)
.error(deferred.reject)
return deferred.promise;
}
return self
}])
Resolve:
resolve : {
friends:['Friends', function(Friends){
return Friends.get();
}]
}
I am not able to update my $scope.gs variable in the view using {{gs}} when I am doing http.get in the service. I tried reading some of the answers but they seem to suggest this method. Please help...
My service method is as below:
app.service('myService', function($http, $rootScope) {
this.getData = function(key){
return $http.get('/myapp/stocklist/AMZN').
then(function(data) {
return data;
});
}
//return this;
});
My controller is:
app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService){
myService.getData($scope.mySelected).then(function(codes){
$scope.gs= codes;
});
}]);
I am not sure if I should use factory instead of Service for this. Can you please advice?
possible to use $q
app.service('myService', function($http, $rootScope, $q) {
return {
getData: function (key) {
var deffered = $q.defer();
$http.get('/myapp/stocklist/AMZN')
.then(function (result) {
deffered.resolve(result.data);
}, function (error) {
deffered.reject(error);
});
return deferred.promise
}
}
});
or adjust your service to
app.service('myService', function($http, $rootScope, $q) {
return {
getData: function (key) {
$http.get('/myapp/stocklist/AMZN')
}
}
});
You use then twice. Try
Service
app.service('myService', function($http, $rootScope) {
this.getData = function(key){
return $http.get('/myapp/stocklist/AMZN');
});
});
Controller
app.controller('graph', ['$scope', '$http', 'myService', function($scope,$http, myService){
myService.getData($scope.mySelected).then(function(response){
$scope.gs= response.data;
});
}]);
I know this is easy, but I can't quite wrap my head around how to do this.
I need to do the API call within a service so that those variables can be accessed between two separate controllers.
The problem I am having is I can't access $routeParams (which I need for the get) within the service. I can't figure out know how to pass $routeParams from the controller to the service.
app.controller('Main', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page;
}]);
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
$scope.Page = Page.posts;
}]);
app.factory('Page', ['$routeParams', '$http', function($routeParams, $http) {
var posts = function posts() {
$http.get('wp-json/wp/v2/pages/?filter[name]='+ $routeParams.slug).success(function(res){
console.log(JSON.stringify(res) );
});
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts
};
}]);
factory :
app.factory('Page', ['$http', function($http) {
var _posts = function posts(param) {
return $http.get('wp-json/wp/v2/pages/?filter[name]='+ param);
};
var description = '';
var title = '';
return {
title: function () { return title; },
setTitle: function (newTitle) { title = newTitle; },
description: function () { return description; },
setDescription: function (newDescription) { description = newDescription; },
posts : _posts
};
}]);
Controller :
app.controller('Pages', ['$scope', 'Page', '$routeParams', '$http', function($scope, Page, $routeParams, $http) {
Page.posts($routeParams.slug).then(function success(response) {
$scope.Page = response.data;
}, function error(reason) {
// do something
});
}]);
please note that success is deprecated in newer versions of Angular. I have updated the code with then
I am trying to achieve category sorting in Angular js but its not working properly. It pulls data from desciption as well. I want to restrict it to categories names but no luck.
JS code:
var myApp = angular.module('myApp', []);
myApp.factory('Items', ['$http', function($http){
return {
get: function(callback){
$http.get('items.json').success(function(data){
callback(data);
})
}
}
}]);
myApp.factory('Categories', ['$http', function($http){
return {
get: function(callback){
$http.get('categories.json').success(function(data){
callback(data);
})
}
}
}]);
// Config and Routes
myApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl:"home.html"
})
.when('/item/:id', {
templateUrl:"item.html"
})
})
myApp.controller('headerController', function($scope, $location) {
$scope.goHome = function () {
$location.path('/');
};
})
function Ctrl($scope) {
$scope.greeting = 'hello';
}
// Controllers
myApp.controller('ItemController', function($scope, $route, $location, $http, Items){
Items.get(function(response){
$scope.items = response;
});
// Update this value dynamically - onclick
$scope.filters = "food";
$scope.viewDetail = function(item) {
$location.path('/item/' + item.id);
}
})
myApp.controller('ListController', function($scope, $route, $location, $http, Categories){
$scope.sendCategory = function(category) {
// How can I pass this value to ItemController?
$scope.search =category.name;
};
$scope.orderProp='date';
$scope.tab = function (tabIndex) {
//Sort by date
if (tabIndex == 1){
//alert(tabIndex);
$scope.orderProp='date';
}
//Sort by views
if (tabIndex == 2){
$scope.orderProp = 'views';
}
};
$scope.sort = function(item) {
if ( $scope.orderProp == 'date') {
return new Date(item.date);
}
return item[$scope.orderProp];
}
})
myApp.controller('CategoryController', function($scope, $route, $location, $http, Categories){
Categories.get(function(response){
$scope.categories = response;
});
})
myApp.controller("tabsController", function ($scope) {
$scope.orderProp = 'date';
})
myApp.controller('ItemDetailController', function($scope, $route, $location, $http, Items){
Items.get(function(response){
$scope.items = response;
if ($route.current.params.id) {
angular.forEach($scope.items, function (v, k) {
if (v.id == $route.current.params.id) {
$scope.currItem = $scope.items[k];
return false;
}
});
}
});
})
can any one please help to find the way I can sort the data only as per my category names instead searching data on the overall pages?
Sharing the reference URL I found for this.
http://plnkr.co/edit/rh3wGYhuoHSHJEa4PoQi?p=preview
It would be great help if any can help me out.