It will fail to bind data from http response if you uncomment "//" line,why? It should be the same, right?
var m = angular.module('users', []);
m.controller('UserList', function($scope) {
// $scope.getdata = function() {
var u = "http://wisebe.duapp.com/admin?queryusers";
var userList = this;
var body = {
activityid: "10",
checkin: $('#checkin').val()
};
$.ajax({
url: u,
type: "post",
async: false,
data: body,
success: function(data) {
userList.users = data;
}
});
// };
// $scope.getdata();
$('#checkin').change(function() {
// $scope.$apply();
});
});
Related
I was trying to parse JSON array in AngularJS. But it's not working. If the array is written directly it's working. Help me to solve the issue. The code I have been using is below.
(function () {
var app = angular.module('store', ['ngCookies']);
app.controller('StoreController', ['$scope', '$cookies', function ($scope, $cookies) {
$scope.products = JSON.parse(SuccessItems);
$scope.cart = [];
$scope.total = 0;
var expireDate = new Date();
expireDate.setDate(expireDate.getDate() + 1);
$cookies.putObject('cart', $scope.cart, { 'expires': expireDate });
$scope.cart = $cookies.getObject('cart');
$scope.total += parseFloat(product.price);
$cookies.put('total', $scope.total, { 'expires': expireDate });
};
}]);
var SuccessItems = '';
$.ajax({
type: "POST",
url: "code.aspx/RetrieveItems",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (jsondata) {
SuccessItems = jsondata.d.replace(/"(\w+)"\s*:/g, '$1:').replace(/"(\d[.]\d+)"/g, "$1");
},
error: function (xhr, ajaxOptions, thrownError) {
errMsg = JSON.parse(xhr.responseText).Message;
alert(baseErrorMsg + 'Error Code : ' + errMsg);
}
})
})();
I was wondering, how could this be written in angularJS?
requests: {
fetchUsers: function() {
return {
url: 'https://www.example.com/api/v2/users',
type: 'GET',
username: 'myemail#email.com/token',
password: 'myAPItoken'
};
}
}
This is just an example:
Your controller:
var userCtrl = angular.module('UserCtrl',[]);
userCtrl.controller('UserController',function($scope,Users){
var getUsers = Users.fetchAll();
getUsers.then(function(response){
$scope.users = response;
});
});
Your service:
var userSrvc = angular.module('UserSrvc',[]);
userSrvc.factory("Users",function($http){
return{
fetchAll: function(){
var request = $http({method:'GET', url:'https://www.example.com/api/v2/users'});
return request;
}
}
});
I have a service class in angular that calls my backend and gets a userInfo as an object. My angular service class has the following.
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'POST'
}
userService.getUserInfo = function (userObj) {
var res = userResource.getUserInfo();
var promises = res.$promise;
return promises;
}
My controller class has the following.
promise = userService.getUserInfo();
promise.then(function (response) {
$scope.user = response;
});
My backends service returns an object.
My problem is I get the user info Object from backend but its not properly wrapped inside a object.the object is mix up with some angular variables. I dont have a response.data .the response object itself has all the information.
$promise: Objectcatch: function (callback) {finally: function (callback) {then: function (callback, errback, progressback) {__proto__:
Object
$resolved: true
about: "sdadsf"
country: "India"
creationDate: "2015-04-07"
email: "user3"
id: 3
industries: Array[2]
name: "user3"
phoneNo: 0
progressLevel: 1
The above response contains $promise and $resolved combined in my object. how can I get my data separately as an object.
controller.js
(function () {
var userController;
userController = function ($scope, userService, searchService) {
var delegate;
var masterUser;
$scope.user = {};
$scope.newEducation = [];
$scope.newProfession = [];
$scope.editMode=false;
$scope.hospitals=[];
$scope.yearOptions={
'year-format': "'yy'",
'starting-day': 1,
'datepicker-mode':"'year'",
'min-mode':"year"
};
$scope.hospit=function(){
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
};
delegate = {
getUserInfo: function () {
userService.getUserInfo(this.onGetUserData,this.onGetError);
},
onGetUserData :function(data){
var usr = (new dcuser(data));
$scope.user = usr;
$scope.masterUser = angular.copy(usr);
},
onGetError :function(data){
alert("error");
},
saveUserInfo:function(){
alert('saveUserInfo');
userService.saveUserInfo($scope.user,this.onSaved);
},
onSaved:function(){
$scope.editMode=false;
},
enableEdit:function(){
$scope.editMode = true;
},
cancelEdit:function(){
angular.copy($scope.masterUser, $scope.user);
$scope.editMode = false;
delegate.getUserInfo();
},
getIndustries :function(){
alert("getIndustries");
},
searchHospitals :function(){
searchService.searchHospitals("a",this.onGetHospitals);
},
onGetHospitals :function(data){
$scope.hospitals = data;
},
searchMedicalSchools :function(){
searchService.searchMedicalSchools("a",this.onGetMedicalSchools);
},
onGetMedicalSchools :function(data){
$scope.medicalSchools = data;
},
connectUser:function(user){
alert("connectUser");
userService.connectUser(user,this.onConnectSuccess,this.onGetError);
},
onConnectSuccess:function(){
alert("connection request sent");
},
initProfieCompletion: function(){
alert("in");
$scope.user.profession = [];
$scope.user.profession.push({
"hospital": "as",
"speciality": "as",
"fromDate": "",
"toDate": ""
});
promise = userService.getHospitals();
promise.then(function (response) {
$scope.hospitals = response.data;
});
},
addEducation:function(){
$scope.newEducation.push({
"medicalSchool": "",
"speciality": "",
"degree": "",
"graduatedYear": ""
});
},
addProfession:function(){
$scope.newProfession.push({
"hospital": "",
"speciality": "",
"fromDate": "",
"toDate": ""
});
}
};
return $scope.delegate = delegate;
}
dc.userModule.controller('userController', userController);
}).call(this);
service.js
(function () {
"use strict";
dc.app.service('userService', ['$rootScope','$resource', '$http', function ($rootScope,$resource, $http) {
var userService = {};
var coreURL = $rootScope.coreURI+'user/';
var userResource = $resource(coreURL+'getFullProfile', {}, {
getUserInfo: {
method: 'GET'
},
saveUserInfo: {
method: 'POST',
url: coreURL+'updateUserInfo'
}
});
var connectResource = $resource(coreURL + 'connectRequest',{}, {
connectUser: {
method: 'POST'
}
});
var userPhotoResource = $resource(coreURL + 'uploadPhoto', {}, {
uploadPhoto: {
method: 'POST'
}
});
userService.getUserInfo = function (onSuccess,onFailure) {
return(userResource.getUserInfo(onSuccess,onFailure));
},
userService.saveUserInfo = function(user,onSuccess){
return userResource.saveUserInfo(user,onSuccess);
},
userService.connectUser = function(user,onSuccess,onFailure){
return connectResource.connectUser(user,onSuccess,onFailure);
},
userService.uploadPhoto =function(image){
var promises = userPhotoResource.uploadPhoto(image);
return promises;
},
userService.getHospitals = function(){
alert('ser');
var promises = $http.get('dcResources/hospitals.json');
return promises;
}
return userService;
}]);
}).call(this);
I have this code in my post.serv.js and in my controller I want to execute the function delete.
"use strict";
app.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
}, {
delete: {
method: 'DELETE',
isArray: false
}
});
return PostResource;
});
I already know how to get and update a post, for example in my createpost.serv.js
"use stric";
app.factory('JnttCreatePost', function ($http, $q, JnttPost) {
return {
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
};
});
and in my newpost.ctrl.js
"use strict";
app.controller('CtrlNewPost',
function ($scope, $location, JnttIdentity, JnttNotifier, JnttCreatePost) {
var email = ...;
$scope.newPost = function () {
var newPostData = {...};
JnttCreatePost.createPost(newPostData).then(function () {
JnttNotifier.notify('success', 'The post has been created');
$location.path('/');
}, function (reason) {
JnttNotifier.notify('error', reason);
});
};
});
I can't realize how to perform the delete request, I can do with a $http
In my new controller for do deletePost() function I have this:
$scope.deletePost = function () {
var pwd = JnttIdentity.currentUser.hashed_pwd;
var postidd = {
password: pwd,
id: $scope.post._id
};
var config = {
method: "DELETE",
url: '/api/post/',
data: postidd,
headers: {
"Content-Type": "application/json;charset=utf-8"
}
};
$http(config);
$location.path('/');
};
This actually already do this stuff but I want to do this without the $http like the create request, How I can do this? How do I can edit this code below for do the request?
createPost: function (newPostData) {
var newPost = new JnttPost(newPostData);
var dfd = $q.defer();
newPost.$save().then(function () {
dfd.resolve();
}, function (response) {
dfd.reject(response.data.reason);
});
return dfd.promise;
}
In my routes.js in express I have this route:
app.delete('/api/post/', posts.deletePost);
You can either call delete on the $resource class you create (JnttPost) or call $delete on a post that's returned from the $resource class.
The $resource class already has get/save/query/remove/delete functions included so you don't need to add the delete (save is create/POST, so you need to include update with PUT).
Here's a sample of using your $resource class to call delete:
angular.module('test', ['ngResource'])
.factory('JnttPost', function ($resource) {
var PostResource = $resource('/api/post/:_id', {
_id: "#id"
}, {
update: {
method: 'PUT',
isArray: false
}
});
return PostResource;
})
.run(function(JnttPost){
JnttPost.delete({id: 123123123});
});
I try to use .then() in my angular controller
angular.module('n2goApp')
.controller('MainCtrl', function($scope, Products) {
Products.get(). then( function ( response ) {
$scope.data = response;
console.log(response);
$scope.totalPages = response.TotalPages;
$scope.totalItems = response.total;
$scope.products = response.data;
$scope.currentPage = response.current_page;
$scope.maxSize = 5;
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
});
});
but drops me an error
Error: Products.get(...).then is not a function
Service
angular.module('n2goApp')
.service('N2goservice', function N2goservice() {
// AngularJS will instantiate a singleton by calling "new" on this function
}).factory('Products', ['$resource', function($resource) {
var url = 'http://domain.com/api/products';
return $resource( url + '/:prodID',
{ bookId: '#prodID' }, {
loan: {
method: 'PUT',
params: { prodId: '#prodID' },
isArray: false
},
get:{
method: 'GET',
params: {
prodId: '#prodID',
page:'#page'
},
isArray: false
}
/* , method3: { ... } */
} );
}]);
What I'm doing wrong?
You have to get the $promise from the resource. Like this:
Products.get().$promise.then(..)
Or you can use the other syntax with callback
Products.get({},function(response) {
});