clear data from inside of callback - javascript

I have the following code snippet. I'm trying to clear the comment, but I can't do it from within the response. Could someone help me to figure out how to do this.
app.controller('CommentController', function($scope, $http) {
$scope.addReview = function(obj) {
this.comment.id = obj.id;
$http.post('/save', this.comment).
then(function(response) {
obj.comments.push(response.data);
this.comment = {};
}, function(response) {
});
};
});

it is because of the scope: 'this' is refering to the 'then' callback.
Try this:
app.controller('CommentController', function($scope, $http) {
$scope.addReview = function(obj) {
// retrieve the scope
var me = this;
this.comment.id = obj.id;
$http.post('/save', this.comment).
then(function(response) {
obj.comments.push(response.data);
// use the upper reference
me.comment = {};
}, function(response) {
});
};
});
Moreover, you would probably use the $scope.$apply function.

Related

Why I am getting not a function error in angularjs?

I am following this tutorial I've found at Stormpath.
I am trying to understand how AngularJS works, but I am failing to get the edit function (controller) running. I am always getting the type error:
TypeError: SearchService.fetch is not a function
Within its callstack it references EditController pointing at this line of code:
SearchService.fetch($stateParams.id, function (response) {
Here is the whole code of EditController:
(function () {
'use strict';
angular
.module('myApp')
.controller('EditController', EditController);
EditController.$inject = ['SearchService', '$stateParams'];
function EditController(SearchService, $stateParams) {
var vm = this;
SearchService.fetch($stateParams.id, function (response) {
vm.person = response;
});
}
})();
However I have no clue what's wrong here. I am trying to compare this code with the code for SearchController - please see below,
(function () {
'use strict';
angular
.module('myApp')
.controller('SearchController', SearchController);
SearchController.$inject = ['SearchService'];
function SearchController(SearchService) {
var vm = this;
vm.search = function(){
SearchService.query(vm.term, function (response) {
var results = response.filter(function (item) {
return JSON.stringify(item).toLowerCase().includes(vm.term.toLowerCase());
});
vm.searchResults = results;
});
}
}
})();
Here is the code for SearchService:
(function () {
'use strict';
angular
.module('myApp')
.factory('SearchService', SearchService);
SearchService.$inject = ['$resource'];
function SearchService($resource) {
return $resource('/api/search/people.json');
}
SearchService.fetch = function (id, callback) {
Search.query(function (response) {
var results = response.filter(function (item) {
return item.id === parseInt(id);
});
return callback(results[0]);
});
};
})();
Any piece of advice is appreciated, I've spent already couple of days trying out various things.
Make your search service like this..
The service factory function generates the single object or function that represents the service to the rest of the application. The object or function returned by the service is injected into any component (controller, service, filter or directive) that specifies a dependency on the service
https://docs.angularjs.org/guide/services
(function () {
'use strict';
angular.module('myApp')
.factory('SearchService', SearchService);
SearchService.$inject = ['$resource'];
function SearchService($resource, $http) {
var service = {};
service.url = $resource('/api/search/people.json');
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
service.fetch = function (id, callback) {
// $http.get('yourapi.json').then() you can try like this also
return $http(req).then(function (response) {
var results = response.filter(function (item) {
return item.id === parseInt(id);
});
return callback(results[0]);
});
};
return service;
}
})();

Dynamic url for $http get

Here is what i try to do :
Json from "urldatas":
[{ "name" : "John" }]
JS file:
var app = angular.module('app', []);
app.service('service', function($http, $q){
this.getDatas = function () {
var datas = $http.get('urldatas', {cache: false});
return $q.all({datas});
};
app.controller('FirstCtrl', function($scope, service, $http, $timeout) {
var vm = this;
vm.loadData = function () {
var promise = service.getDatas();
promise.then(function (data) {
$scope.datas = data.datas.data;
console.log($scope.datas);
});
};
vm.loadPackages = function () {
var url = "urlPackages" + datas.name;
$http.get(url).then(function (response) {
$scope.MyPackages = response.data;
});
};
So i try to dynamicly change url in $http.get in getPackages, by values from getDatas, but i don't know how to do it. url in console shows "urlPackagesundefinded". Thanks for answers in advance.
$q send multiple requests as an array, not as an object. remove the curly bracket and add a square bracket
var datas = $http.get('urldatas', {cache: false});
return $q.all([datas]);
since you reference the controllerAs remove the scope variables and reference them through vm.
also in then promises response data comes under data property
var promise = service.getDatas();
promise.then(function (response) {
vm.datas = response.data.datas.data;
console.log(vm.datas);
});

AngularJS: Update array after submitting a new object

I need to update an array after I save an object by replacing the push method. I tried to use a function instead of the push method but it doesn't work. Any ideas on how to fix that?
app.controller("productController", function($scope, $http, createProductService, listProducstService){
$scope.addProduct = function(){
var newProduct = createProductService.createProduct($scope.product);
//$scope.products.push(newProduct);
updateArray();
};
$scope.products = listProductsService.query();
var updateArray = function(){
$scope.products = listProductsService.query();
}
}
app.factory("listProductsService", function($resource){
return $resource("getAllProducts", {}, {
listProducts: {
method: "GET",
isArray: true
}
})
})
you need to use $scope.$apply() :
var updateArray = function(){
$scope.$apply(function () {
$scope.products = listProductsService.query();
});
}
http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

how to call method inside $http body angularjs

I want to call editopenComponentModal in my other method its show error angular.js:13920 TypeError: Cannot read property 'editopenComponentModal' of undefined
EditCurrentJob(job) {
this.$http.put(properties.job_path + "/"+job.job_id).then(function successCallback(response) {
console.log(response.data);
this.current_job = response.data;
this.editopenComponentModal();
},
function errorCallback(response) {
});
}
editopenComponentModal() {
var modalInstance = this.$uibModal.open({
animation: this.animationsEnabled,
template: require('./Report/editsubmittedinformation.html'),
scope: this.$scope,
size: 'lg'
});
this.$scope.modalInstance = modalInstance;
return modalInstance.result;
}
Use the function references for that purpose, jopefully this will help you out.
var vm = this;
vm.editopenComponentModal = editopenComponentModal;
function EditCurrentJob(job) {
$http.put(properties.job_path + "/"+job.job_id).then(function successCallback(response) {
console.log(response.data);
vm.current_job = response.data;
vm.editopenComponentModal();
},
function errorCallback(response) {
});
}
function editopenComponentModal() {
var modalInstance = this.$uibModal.open({
animation: this.animationsEnabled,
template: require('./Report/editsubmittedinformation.html'),
scope: this.$scope,
size: 'lg'
});
this.$scope.modalInstance = modalInstance;
return modalInstance.result;
}
If you want to open a modal after $http.put request then use.
$('#success').modal();
here success is the id.
Add var that = this above the this.$http.put(
Then change:
this.current_job = response.data;
this.editopenComponentModal();
To:
that.current_job = response.data;
that.editopenComponentModal();
Explanation:
this inside the callback has different context, so you need to save the desired this to a variable which can be used there.
Here you can read the better explanation:
How to access the correct `this` context inside a callback?

Pass value from provider to controller in angularJs

I'm trying get data from db to UI. Url given via provider is getting the data.
Controller in controller DetailsProvider.getDashboardDetails() is getting null.
var appmod = angular.module('project.DetailDashboardController', []);
appmod.controller("DetailDashboardController", ['$rootScope', '$scope', '$state', 'DetailsProvider',function($rootScope, $scope, $state,DetailsProvider) {
console.log("DetailDashboardController --- ");
$scope.DetList= DetailsProvider.getDashboardDetails()
}]);
})(window, window.angular);
provider which will call the list
(function(angular) {
var appmod = angular.module('project.DetailsServiceProvider', []);
appmod.provider('DetailsProvider', function() {
this.$get = ['_$rest', function DetailServiceFactory(_$rest) {
return new DetailsProvider(_$rest);
}];
});
function DetailsProvider(_$rest) {
this._$rest = _$rest,
this.getDashboardDetails = function(_callback, _data) {
var newData = null;
_$rest.post({
url: window.localStorage.getItem('contextPath') +'home/listdetail',
data: {} ,
onSuccess:_callback
}
});
}
};
})(window.angular);
Thanks in advance for any kind of reply!
You should return promise from your service method and do thenable in your controller.
Root Cause : your are returning the newData which will initalized later after completing the ajax call.Before completing it,you are returning the same variable which will be always null.
In provider,
(function(angular) {
var appmod = angular.module('project.DetailsServiceProvider', []);
appmod.provider('DetailsProvider', function() {
this.$get = ['_$rest', function DetailServiceFactory(_$rest) {
return new DetailsProvider(_$rest);
}];
});
function DetailsProvider(_$rest) {
this._$rest = _$rest,
this.getDashboardDetails = function(_callback, _data) {
var newData = null;
_$rest.post({
url: window.localStorage.getItem('contextPath') +'home/listdetail',
data: {} ,
onSuccess:_callback
}
});
}
};
})(window.angular);
and in controller,
$scope.list = function() {
DetailsService.getDashboardDetails(function(data){
varr holdIt = data.data.DList;
});
};

Categories