Force update on rzModule sliders in AngularJS - angularjs

I have a few sliders in an angularJS app. What I try to achieve is when the user change the option on a select dropdown, the sliders should get an update with new values from a RestAPI.
This example is for one of the sliders, but the rest are the same.
Creating the slider on controller
myCtrl.ageSlider = {
value: 17,
options: {
showSelectionBar: true,
ceil: 38,
hideLimitLabels: true,
floor: 17,
onChange: myCtrl.getResults,
getPointerColor: function(value) {
return '#FFCF00'
},
getSelectionBarColor: function(value) {
return '#FFCF00'
}
}
};
The update function on controller which is called on ng-change of the select
myCtrl.updateSliders = function () {
//other sliders here that don't need a call on API
StaffServices.getMedic(myCtrl.selected.id,
function(response) {
myCtrl.ageSlider.value = parseInt(response.data.age);
myCtrl.getResults();
},
function(response) {
console.log('Something went wrong on medic process');
});
}
And the getResults() function which call a service
myCtrl.getResults = function() {
myCtrl.results = myService.myUpdatesCalc(passSomeValues);
}
When I manually change the slider from the user interface, the onChange fires the getResults function. Spending hours on this and cannot find the reason. Any help?
Edit: This is the service getMedic to avoid any confusion
service.getMedic = function(id, onSuccess, onError) {
$http.get(API_Base + 'api/staff/medic?id='+id,
{
headers: { 'Authorization': 'Bearer '+$cookies.get('token')}
}).
then(function(response) {
onSuccess(response);
}, function(response) {
onError(response);
});
}

Angular $http return promises, and hence your values are not updated. You will need to handle the promises, and then update it at the callback function:
myCtrl.getResults = function() {
myService.myUpdatesCalc(passSomeValues) //this is your REST API, will return a promise
.then(function(response) { //this is the callback function to handle the successful ajax
myCtrl.results = response.data; //update your results here!
}, function(error) { //this is the callback function to handle the failed ajax
console.log('error')
})
}

Related

How to intercept convenience shortcuts of $http in AngularJS

I have the following function (credit) that wraps an AngularJS $http function in a way that it invokes browser XHR when running on desktop, but invokes cordova-plugin-advanced-http if on mobile.
It seems that this works when I use $http({method:'get/post'}...) but doesn't work if I call the convenience shortcuts like $http.get(...)
Can someone suggest what modification I need to make?
$provide.decorator('$http', ['$delegate', '$q', function($delegate, $q) {
// create function which overrides $http function
var $http = $delegate;
var wrapper = function () {
var url = arguments[0].url;
var method = arguments[0].method;
var isOutgoingRequest = /^(http|https):\/\//.test(url);
if (window.cordova && isOutgoingRequest) {
console.log ("**** -->"+method+"<-- using native HTTP with:"+url);
var d = $q.defer();
var options = {
method: method,
data: arguments[0].data,
headers: arguments[0].headers,
timeout: arguments[0].timeout
};
cordova.plugin.http.sendRequest(url,options,
function (succ) {
console.log ("*** Inside native HTTP success with:"+JSON.stringify(succ));
try {
if (options.headers && options.headers['x-parse']=='text')
d.resolve({"data":succ.data});
else
d.resolve({"data":JSON.parse(succ.data)});
return d.promise;
}
catch (e) {
d.resolve({"data":succ.data});
return d.promise;
}
},
function (err) {
console.log ("*** Inside native HTTP error");
d.reject(err);
return d.promise;
});
return d.promise;
}
else {
console.log ("**** "+method+" using XHR HTTP for "+url);
return $http.apply($http, arguments);
}
};
Object.keys($http).filter(function (key) {
return (typeof $http[key] === 'function');
}).forEach(function (key) {
wrapper[key] = function () {
// Apply global changes to arguments, or perform other
// nefarious acts.
// console.log ("KEY="+key);
return $http[key].apply($http, arguments);
};
});
return wrapper;
}]);
If I understood your intent correctly, the way you're assigning the HTTP methods that hang off wrapper won't invoke the contents of your wrapper function.
Note that the parameters of the $http convenience functions vary.
Examples:
GET is described as: get(url, [config])
POST is described as: post(url, data, [config])
With the above in mind, here's one way of delegating back to your wrapper function that switches between XHR and the Cordova plugin when the $http convenience methods are used:
wrapper[key] = function () {
var url = arguments[0];
if (['get', 'delete', 'head', 'jsonp'].indexOf(key) !== -1) {
// arguments[1] == config
return wrapper(Object.assign({
method: key,
url: url,
}, arguments[1]));
} else {
// POST, PUT, PATCH
// arguments[1] == data
// arguments[2] == config
return wrapper(Object.assign({
data: arguments[1],
method: key,
url: url,
}, arguments[2]));
}
};
Here is a working solution I eventually arrived at.
// Wraps around $http that switches between browser XHR
// or cordova-advanced-http based on if cordova is available
// credits:
// a) https://www.exratione.com/2013/08/angularjs-wrapping-http-for-fun-and-profit/
// b) https://gist.github.com/adamreisnz/354364e2a58786e2be71
$provide.decorator('$http', ['$delegate', '$q', function($delegate, $q) {
// create function which overrides $http function
var $http = $delegate;
var wrapper = function () {
var url;
var method;
url = arguments[0].url;
method = arguments[0].method;
var isOutgoingRequest = /^(http|https):\/\//.test(url);
if (window.cordova && isOutgoingRequest) {
console.log ("**** -->"+method+"<-- using native HTTP with:"+encodeURI(url));
var d = $q.defer();
var options = {
method: method,
data: arguments[0].data,
headers: arguments[0].headers,
timeout: arguments[0].timeout,
responseType: arguments[0].responseType
};
cordova.plugin.http.sendRequest(encodeURI(url),options,
function (succ) {
// automatic JSON parse if no responseType: text
// fall back to text if JSON parse fails too
if (options.responseType =='text') {
// don't parse into JSON
d.resolve({"data":succ.data});
return d.promise;
}
else {
try {
d.resolve({"data":JSON.parse(succ.data)});
return d.promise;
}
catch (e) {
console.log ("*** Native HTTP response: JSON parsing failed for "+url+", returning text");
d.resolve({"data":succ.data});
return d.promise;
}
}
},
function (err) {
console.log ("*** Inside native HTTP error: "+JSON.stringify(err));
d.reject(err);
return d.promise;
});
return d.promise;
}
else { // not cordova, so lets go back to default http
console.log ("**** "+method+" using XHR HTTP for "+url);
return $http.apply($http, arguments);
}
};
// wrap around all HTTP methods
Object.keys($http).filter(function (key) {
return (typeof $http[key] === 'function');
}).forEach(function (key) {
wrapper[key] = function () {
return $http[key].apply($http, arguments);
};
});
// wrap convenience functions
$delegate.get = function (url,config) {
return wrapper(angular.extend(config || {}, {
method: 'get',
url: url
}));
};
$delegate.post = function (url,data,config) {
return wrapper(angular.extend(config || {}, {
method: 'post',
url: url,
data:data
}));
};
$delegate.delete = function (url,config) {
return wrapper(angular.extend(config || {}, {
method: 'delete',
url: url
}));
};
return wrapper;
}]);

Angular Spinner Usage Without using timeout

I have a problem with angular spinner here, i have a update button inthat i'm using spin and loading needs to be stopped after saving the data in to database without using any timeout function i need stop that loading
function assignLectureToSubject(subject) {
subject.$update();
}
above code is the function for update button
Use a flag. lets call it isUpdating
$scope.isUpdating = false;
function update(){
$scope.isUpdating = true;
$http({
method: 'POST',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.isUpdating = false;
}, function errorCallback(response) {
$scope.isUpdating = false;
});
}
And in the HTML,
<your-spinner ng-show='isUpdating'>
Initially, spinner is hidden. When update is called, the spinner starts showing on the page. And when the event completes, the callback sets the flag to false, thereby hiding it again.
You can implement a genric solution, You can use interceptors, Here is an example. Perform your operation for ShowWaitIndicator and HideWaitIndicator functions
app.factory('waitingInterceptor', ['$q', '$rootScope',
function ($q, $rootScope) {
return {
request: function (config) {
ShowWaitIndicator();
return config || $q.when(config);
},
requestError: function(request){
HideWaitIndicator();
return $q.reject(request);
},
response: function (response) {
HideWaitIndicator();
return response || $q.when(response);
},
responseError: function (response) {
HideWaitIndicator();
return $q.reject(response);
}
};
}]);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('waitingInterceptor');
}]);

Ajax in AngularJS Service

Created an Angular Service:
calculator_app.service('FillOpportunity', function () {
this.fill_opportunity = function (path,scope) {
$.ajax({
url: 'opportunitycalculator/calculator/GetProducts?idstring=' + path,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
scope.opportunity_data = data;
scope.$apply();
},
error: function () {
}
});
};
});
Called the service on ng-change of a dropdown:
FillOpportunity.fill_opportunity($scope.result_path,$scope);
The scope.opportunity_data is binded to the select in UI:
<select id="seloppurtunityproducts" name="selproducttype" multiple="" style="height:300px" ng-model="opportunity_products" ng-options="a for a in opportunity_data"></select>
On ng-Change, Ajax is called when I check in Network of Chrome, but the value is not updated in the select box.
Any inputs?
Don't use jQuery's ajax. Use the built in $http. Using $http automatically begins the digest cycle of angular's builtin compiler. If you must use jquery... then you'd have to call $scope.$apply(); every time there is a data change.
Service:
calculator_app.factory("calcService", ["$http", function($http) {
return {
getItem: function(url, items) {
return $http.get(url,
// query string like { userId: user.id } -> ?userId=value
{ params: items });
}
}
}]);
Inject the service into your controller and use:
calculator_app.controller("MainCtrl", ["calcService", "$scope", function(calcService, $scope) {
$scope.opportunity_data = [];
var payload = {
idstring: path
};
//call the service
calcService.getItem('path/to/calc/api', payload).then(function(response) {
$scope.opportunity_data = response.data;
}).catch(function(response) {
alert('error' + response.data);
});
}]);

How to get the data for my controller when http request in progress?

I have following controller
1) introCtrl
2) ArticleCtrl
3) articleService (Service)
Now I am sending an http request from introCrtl
.controller('IntroCtrl', function($scope, articleService) {
articleService.getArticles();
});
and AricleCtrl is
.controller('ArticleCtrl', function($scope,$rootScope,articleService) {
$scope.articles = articleService.fetchArticles();
})
and my Service is
.service('articleService', function ($http, $q) {
var articleList = [];
var getArticles = function() {
$http({
url: "muylink,co,",
data: { starLimit: 0, endLimit: 150,created_date: 0 },
method: 'POST',
withCredentials: true,
}).success(function (data, status, headers, config) {
articleList.push(data);
}).error(function (err) {
console.log(err);
})
};
var fetchArticles = function() {
return articleList[0];
}
return {
getArticles: getArticles,
fetchArticles: fetchArticles
};
});
Which is also working fine. Now Problem is that
Sometimes my http request sending respone late and i got nothing in
$scope.articles.
Can we implement watch here. How i need to implement $watch here. I dont want to implement promise. because i want to run http request behind the scene.
Thanks
It would be better if you switch to a state based setup with ui-router that way you can do this :
$stateProvider.state('myState', {
url: 'the/url/you/want',
resolve:{
articleService: 'articleService' // you are dependency injecting it here,
articles: function (articleService) {
return articleService.getArticles.$promise;
}
},
controller: 'IntroCtrl'
})
// then your controller can just inject the articles and they will be resolved before your controller loads so you it will always be fetched prior
.controller('IntroCtrl', function($scope, articles) {
$scope.articles = articles;
});
for more information take a look at this
ui-router info
All to do is set watch on articleList and provide maintaining function.
As you are watching array, it's good to change it to string.
Create function in watch which results array.
$scope.$watch( function() {
return JSON.stringify($scope.articleList);
}, function(newVal,oldVal){
//provide logic here
});
If your service result is asynchron (like http requests) you should return promises from your service.
.controller('ArticleCtrl', function($scope,$rootScope,articleService) {
articleService.fetchArticles().then(function(articles) {
$scope.articles = articles;
});
})
Service
// not sure about your service logic... simplified:
.service('articleService', function ($http, $q) {
var articleListPromise ;
var getArticles = function() {
articleListPromise = $http(/* ...*/);
};
var fetchArticles = function() {
return articleListPromise.then(function(data) {
return data[0];
});
}
return {
getArticles: getArticles,
fetchArticles: fetchArticles
};
});

AngularJS: Refreshing service result

I have a service getting items by $http. In the controller I share this data with the view. It works, but when I delete or add new items by $http, I cannot get my list to stay up to date.
I created a refresh() function, that I call every time I add or delete an item, but the refresh applies only from time to time. And not on every action though the function is always duly called and executed.
How should I proceed to get my items refreshed on every action?
Function:
refresh = function() {
itemsService.getItems().then(function(d) {
$scope.items= d;
});
}
Service:
app.factory('itemsService', function($http) {
var itemsService = {
getItems: function() {
return $http.get('items.json')
.then(
function (response) {
return response.data;
}
);
}
};
return itemsService;
});
I have also read about $watch() and tried to make it work in this case, but it does not seem to make any difference:
$scope.$watch('itemsService.getItems()', function(d) {
$scope.items = d;
}, true);
This might be what you are looking for
Angular JS - listen or bind $http request
You can just call your function when the request ends.
You can use an interceptor to do this
var httpinterceptor = function ($q, $location) {
return {
request: function (config) {
//show your loading message
console.log(config);
return config;
},
response: function (result) {
//hide your loading message
console.log('Repos:', result);
return result;
},
responseError: function (rejection) {
//hide your loading message
console.log('Failed with', rejection);
return $q.reject(rejection);
}
}
};
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(httpinterceptor);
});

Resources