refresh button not working in Angular - javascript

I want to have a button that refresh a page (request to http to load data) :
http://plnkr.co/edit/Ol6iEoLp037ZHu0P40Wr?p=preview
refresh button with Factory - - not working
$scope.doRefresh = function() {
Content.content.success(function(data){
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
});
Now when you delete some data and want to have theme back you should hit refresh button but it's not working .
working demo
http://plnkr.co/edit/WHSEPxyQDi3YNkEP8irL?p=preview
$scope.doRefresh = function() {
$http.get("data.json")
.success(function(data) {
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
})
}
now it's working with $http
I want to do it with factory , but i can't handle this , Any advice ?
Update *****
Factory
app.factory('Content', function ($http) {
return {
content: $http.get('data.json')
}
})

You've got to tell your service to retrieve the data every time the content is requested.
app.factory('Content', function ($http, $q) {
return {
getContent: function() {
var deferred = $q.defer();
$http.get('data.json').succes(function(data) {
deferred.resolve(data);
});
return deferred.promise;
}
}
})
Then in your controller you can do:
$scope.doRefresh = function() {
Content.getContent().then(function(data) {
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
});
You can also just cache the data in your factory and return it without doing a request:
app.factory('Content', function($http, $q, $timeout) {
var originalData;
return {
getContent: function() {
var deferred = $q.defer();
if (!originalData) {
$http.get('data.json').succes(function(data) {
originalData = data;
deferred.resolve(data);
});
} else {
/// gonna use timeout to simulate async behaviour -- kinda hacky but it makes for a pretty interface
$timeout(function() {
defered.resolve(originalData);
}, 0);
}
return deferred.promise;
}
}
})
Careful though, changes done to the returned object will affect the originalData object.

app.factory('Content', function ($http) {
function getContent(onSuccess) {
$http.get('data.json').success(function (data) {
if (onSuccess) {
onSuccess(data)
}
}
}
return {
content: getContent
}
})
in your controller:
$scope.doRefresh = function () {
Content.content(function (data) {
$scope.data = data.artists;
console.log($scope.data);
$scope.$broadcast('scroll.refreshComplete');
});
};

Related

Send data through a POST request from Angular factory

I have this in the controller
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
$scope.formTodoText = '';
};
});
and this in the factory
angular.module('myApp')
.factory('TaskFactory', function ($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
console.log(1, params);
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log(2);
console.log('data', data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTask: function(taskData) {
console.log('taskData', taskData);
return sendTasks('/task/save', {
taskData : taskData
})
}
}
});
all I need is to know, how to send the data from the controller to the factory in order to do the POST to the specified route ?
You just need to call the function/method inside factory with the required params.
angular.module('myApp')
.controller('TaskController', function ($scope, TaskFactory) {
$scope.addTodo = function () {
$scope.todos.push({text : $scope.formTodoText});
TaskFactory.sendTask({data : $scope.formTodoText})
$scope.formTodoText = '';
};
});
You can follow Dan Wahlin blog post.
Controller:
angular.module('customersApp')
.controller('customersController', ['$scope', 'dataFactory', function ($scope, dataFactory) {
$scope.status;
dataFactory.updateCustomer(cust)
.success(function () {
$scope.status = 'Updated Customer! Refreshing customer list.';
})
.error(function (error) {
$scope.status = 'Unable to update customer: ' + error.message;
});
}
Factory:
angular.module('customersApp')
.factory('dataFactory', ['$http', function($http) {
var urlBase = '/api/customers';
dataFactory.updateCustomer = function (cust) {
return $http.put(urlBase + '/' + cust.ID, cust)
};
}
Hope that solve your problem.
You can call the function directly on the TaskFactory that you pass into the controller as a dependency.
I've cleaned up your code a bit and created a plunk for you here:
And here's the code:
Controller
(function(angular) {
// Initialise our app
angular.module('myApp', [])
.controller('TaskController', function($scope, TaskFactory) {
// Initialise our variables
$scope.todos = [];
$scope.formTodoText = '';
$scope.addTodo = function() {
// Add an object to our array with a 'text' property
$scope.todos.push({
text: $scope.formTodoText
});
// Clear the input
$scope.formTodoText = '';
// Call function to send all tasks to our endpoint
$scope.sendTodos = function(){
TaskFactory.sendTasks($scope.todos);
}
};
});
})(angular);
Factory
(function(angular) {
angular.module('myApp')
.factory('TaskFactory', function($q, $http) {
var sendTasks = function(params) {
var defer = $q.defer();
$http.post('http://localhost:3000/task/save', params)
.success(function(data) {
console.log('data: ' + data);
})
.error(function(err) {
defer.reject(err);
});
return defer.promise;
}
return {
sendTasks: sendTasks
}
});
})(angular);

How do I call a custom get method

I'm listing users with:
/api/users/
I'd like to list users who are admins by calling:
/api/users/admins
As trivial as it may seem, I can't find a way to do this.
I do not know which programming language you are using, but I'm going to give you an example using PHP Laravel, and AngularJS.
API
Route::get('/api/users', function ()
{
$users = App\User::all();
return $users;
});
Route::get('/api/users/admin', function ()
{
$users = App\User::where('admin', true)->get();
return $users;
});
FRONT
angular.module('app', [])
.service('api', ['$http', function ($http) {
function getUsers() {
return $http.get('/api/users');
}
function getAdminUsers() {
return $http.get('/api/users/admin');
}
this.getUsers = getUsers;
this.getAdminUsers = getAdminUsers;
}])
.controller('UserCtrl', ['$scope', 'api', function ($scope, api) {
$scope.users = [];
$scope.adminUsers = [];
api.getUsers()
.then(function success(response) {
$scope.users = response.data;
}, function error(response) {
});
api.getAdminUsers()
.then(function success(response) {
$scope.adminUsers = response.data;
}, function error(response) {
});
}]);
Sorry about the lack of details in my question. I was actually asking the question about the angular-restmod module.
Here's what I did in the end:
module.factory('CustomMethods', ['restmod', 'RMUtils', function CustomMethodsMixin(restmod, RMUtils) {
return restmod.mixin(function() {
this.define('Model.$customCollection', function(_url, params) {
var original = this;
return this.$collection(params, {
$urlFor: function() {
return RMUtils.joinUrl(original.$url(), _url);
}
});
});
return this;
});
}]);
And expose all my api to it:
restmodProvider.rebase('CustomMethods')

Angular Factory Not passing data back

I am trying to create an Angular Factory, this is based on a example from a plural site course http://www.pluralsight.com/training/player?author=shawn-wildermuth&name=site-building-m7&mode=live&clip=3&course=site-building-bootstrap-angularjs-ef-azure.
From debugging the code in Chrome it appears to run fine. I can see when I debug it that the service gets my data and puts it in my array but when I look at the controller in either $scope.data or dataService.data the arrays are empty. I don't see any javascript errors. I'm not sure what I'm doing wrong, any suggestions. I'm using AngularJS v1.3.15.
module.factory("dataService", function($http,$routeParams,$q) {
var _data = [];
var _getData = function () {
var deferred = $q.defer();
$http.get("/api/v1/myAPI?mainType=" + $routeParams.mainType + "&subType=" + $routeParams.subType)
.then(function (result) {
angular.copy(result.data,_data);
deferred.resolve();
},
function () {
//Error
deferred.reject();
});
return deferred.promise;
};
return {
data: _data,
getData: _getData
};});
module.controller('dataController', ['$scope', '$http', '$routeParams', 'dataService',function ($scope, $http, $routeParams, dataService) {
$scope.data = dataService;
$scope.dataReturned = true;
$scope.isBusy = true;
dataService.getData().then(function () {
if (dataService.data == 0)
$scope.dataReturned = false;
},
function () {
//Error
alert("could not load data");
})
.then(function () {
$scope.isBusy = false;
})}]);
On
return {
data: _data,
getData: _getData
};});
you have "data: _data," while your array is named just "data". Change the name of the variable to match and it will work:
var _data = [];
Why would you use deferred from $q this way?
The proper way to use $q:
$http.get("/api/v1/myAPI?mainType=" + $routeParams.mainType + "&subType=" + $routeParams.subType)
.success(function (result) {
deferred.resolve(result);
}).error(
function () {
//Error
deferred.reject();
});
And then in controller
dataService
.getData()
.then(function success(result) {
$scope.data = result; //assing retrived data to scope variable
},
function error() {
//Error
alert("could not load data");
});
In fact, there are some errors in your codes :
In your Service, you define var data = [];, but you return data: _data,. So you should correct the defination to var _data = []
you don't define _bling, but you use angular.copy(result.data,_bling);
One more question, why do you assigne the service to $scope.data : $scope.data = dataService ?
EDIT :
Notice that there 3 changes in the following codes:
comment the $scope.data = dataService;, because it makes no sense, and I think that $scope.data should be the data that the service returns.
$scope.data = dataService.data;, as I described in 1st point. You can see the result from the console.
In the if condition, I think that you want to compare the length of the returned data array, but not the data.
module.controller('dataController', ['$scope', '$http', '$routeParams', 'dataService',function ($scope, $http, $routeParams, dataService) {
// $scope.data = dataService;
$scope.dataReturned = true;
$scope.isBusy = true;
dataService.getData().then(function () {
if (dataService.data.length === 0){
$scope.dataReturned = false;
}else{
$scope.data = dataService.data;
console.log($scope.data);
}
},
// other codes...
})}]);

Wait till $http is finished in order to output the result in AngularJS

How can I wait with my function till the $http request is finished?
My services.js looks as follows:
var app = angular.module('starter.services', []);
app.factory('Deals', function($http) {
function getDeals() {
$http.get('http://www.domain.com/library/fct.get_deals.php')
.success(function (data) {
var deals = data;
return deals;
})
.error(function(err){
});
}
return {
all: function() {
return getDeals();
},
get: function(keyID) {
//...
}
}
});
My controllers.js looks like:
var app = angular.module('starter.controllers', []);
app.controller('DealCtrl', function($scope, Deals) {
$scope.deals = Deals.all();
console.log($scope.deals);
});
The console.log in my controllers.js file outputs "undefined", but when I output the deals in the getDeals() function it contains the correct array which I get from my server.
What am I doing wrong?
$http and all of the async services in angularjs return a promise object. See promise api.
You need to use then method to assign it to a value in the scope.
So your controller:
app.controller('DealCtrl', function($scope, Deals) {
Deals.all().then(function (deals) {
$scope.deals = deals;
console.log($scope.deals);
});
});
Your service
app.factory('Deals', function($http) {
function getDeals() {
return $http.get('http://www.domain.com/library/fct.get_deals.php')
.success(function (data) {
var deals = data;
return deals;
});
}
return {
all: function() {
return getDeals();
},
get: function(keyID) {
//...
}
}
});

Angular Promise ($q) is not working

I am trying to use Angular with SignalR in my demo application. I am trying to use $q service to use promises. Don't know whats wrong in my code but its not working.
SERVICE
var boardConsole = $.connection.builtinboard;
var chat = angular.module('chat', []);
chat.factory('board', ['$q', '$timeout', function ($q, $timeout) {
var board = {};
board.startBoard = function (callback) {
$.connection.hub.start(function () {
if (angular.isFunction(callback)) {
callback();
}
});
};
board.loadAllMessages = function () {
var deferred = $q.defer();
boardConsole.server.loadAllMessages().done(function (messages) {
deferred.resolve(messages);
}).fail(function () {
deferred.reject(function () {
//SHOW NOTHING FOUND
});
});
return deferred.promise;
};
return board;
} ]);
CONTROLLER
chat.controller('chatController', ['$scope', 'board', function ($scope, board) {
$scope.Messages = [];
board.startBoard(function () {
board.loadAllMessages().then(function (messages) {
alert('1');
$scope.Messages = messages;
});
});
} ]);
its not working
Just wrap it in a $timeout. This will perform a safe $apply if necessary.
$timeout(function(){
deferred.resolve(messages);
});

Categories

Resources