I'm trying to post new data comment and I want $resource serviceto give every comment unique id automatically.but I don't know how to do it . the data was past but in id was property empty ,it don't have id number.
Code for controller.js
.controller('ContactController', ['$scope','FeedbackFactory', function($scope,FeedbackFactory) {
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" ,id:""};
var channels = [{value:"tel", label:"Tel."}, {value:"Email",label:"Email"}];
$scope.channels = channels;
$scope.invalidChannelSelection = false;
$scope.fback= FeedbackFactory.putFeedback().query(
function(response){
$scope.fback = response;
},
function(response) {
$scope.message = "Error: "+response.status + " " + response.statusText;
}
);
}])
.controller('FeedbackController', ['$scope', 'FeedbackFactory',function($scope,FeedbackFactory) {
$scope.sendFeedback = function() {
console.log($scope.feedback);
if ($scope.feedback.agree && ($scope.feedback.mychannel === "")) {
$scope.invalidChannelSelection = true;
console.log('incorrect');
}
else {
$scope.invalidChannelSelection = false;
$scope.fback.push($scope.feedback);
FeedbackFactory.putFeedback().save($scope.fback);
$scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" };
$scope.feedback.mychannel="";
$scope.feedbackForm.$setPristine();
console.log($scope.feedback);
}
};
}])
service.js
.service('FeedbackFactory',['$resource','baseURL',function($resource,baseURL){
this.putFeedback = function(){
return $resource(baseURL+"feedback/",{'update':{method:'POST'}});
};
} ])
;
note:the data comment will save in form of JSON data.
Related
i have a problem with saving JSON on a scope, I have already a function saving a JSON into a scope and works perfectly but the second one won't save...
servicoLeituraPosts.php returns JSON with data
servicoLeituraComments.php returns JSON with data
both send JSON through URL correctly, and the first shows data on scope, but the second one doesn't and it's done exactly like the first one, so I don't understand what is going on.
1st one saves JSON into $scope.posts, it has data and i can print it
2nd one saves JSON into $scope.comments, if i print it, it is blank? Why? Thank you for help but I'm a beginner in AngularJS.
<script>
var app = angular.module('postsApp', []);
var interval;
app.controller('postsCtrl', function($scope) {
$scope.toggle = false;
$scope.texto = [];
$scope.comment = [];
$scope.comment = "";
$scope.comments = [];
$scope.posts = [];
$scope.texto = "";
$scope.idPost = 0;
$scope.showBox = function(p){
p.toggle = !p.toggle;
if(interval == 0){
interval = setInterval("angular.element($('#postsApp')).scope().servicoLeituraPosts()",1000);
}else{
clearInterval(interval);
interval = 0;
}
$scope.servicoLeituraComments(p);
console.log($scope.comments);
console.log($scope.posts);
};
$scope.iniciaTimer = function(){
interval = setInterval("angular.element($('#postsApp')).scope().servicoLeituraPosts()",1000);
};
$scope.servicoLeituraPosts = function(){
$.getJSON(
"servicoLeituraPosts.php",
{
},
function(jsonData)
{
$scope.posts = jsonData;
$scope.$apply();
});
};
$scope.servicoLeituraComments = function(p){
$.getJSON(
"servicoLeituraComments.php",
{
"idPost": p.idPost
},
function(jsonData)
{
$scope.comments = jsonData;
$scope.$apply();
});
console.log($scope.comments);
};
$scope.addPost = function(){
$.post(
"addPostRest.php",
{
"texto" : $scope.texto
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
$scope.addLike = function(idPost){
$.post(
"addLike.php",
{
"idPost" : $scope.idPost = idPost
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
$scope.addComment = function(p){
$.post(
"addComentarioRest.php",
{
"comment" : p.comment,
"idPost" : p.idPost
},
function(dados)
{
$scope.texto = dados.indexOf("OK") >= 0 ? "" : "FALHOU";
$scope.$apply();
}
);
};
});
</script>
Found the solution, apparently there was a problem with the parameter recieved on POST which made the JSON invalid having no data
It looks like you are calling console.log($scope.comments); synchronously after calling $.getJSON(...), rather than waiting for the jsonData to be returned. At this point the $scope is yet to be updated.
Try moving the console.log into the callback:
function(jsonData)
{
$scope.comments = jsonData;
$scope.$apply();
console.log($scope.comments);
});
var app=angular.module('myApp',[]);
app.controller('FCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.showPerson = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.persons = mockFactory.array;
})
}
$scope.delPerson = function(i){
mockFactory.delete(i);
}
$scope.addNamePerson = function() {
mockFactory.ADD($scope.valueFirst);
};
$scope.showConsolePerson= function(){
console.log(JSON.stringify(mockFactory.array));
}
}]);
app.controller('SCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.showMovie = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.movies = mockFactory.array;
})
}
$scope.delMovie = function(i){
mockFactory.delete(i);
}
$scope.addNameMovie = function() {
mockFactory.ADD($scope.valueSecond);
};
$scope.showConsoleMovie= function(){
console.log(JSON.stringify(mockFactory.array));
}
}]);
app.controller('TCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.showPlace = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.places = mockFactory.array;
})
}
$scope.delPlace = function(i){
mockFactory.delete(i);
}
$scope.addNamePlace = function() {
mockFactory.ADD($scope.valueThird);
};
$scope.showConsolePlace= function(){
console.log(JSON.stringify(mockFactory.array));
}
}]);
app.factory('mockFactory',['$http',function($http){
var Precord = {};
Precord.array = [];
Precord.assign = function (value) {
return $http.get('http://localhost:3000/scripts/' + value + '.json');
};
Precord.fetchJson = function(value){
return Precord.assign(value).success(function(response){
Precord.array = response.value;
})
}
Precord.delete = function(i){
Precord.array.splice(i,1);
}
Precord.ADD = function(value){
var newName = {
Name: value
};
Precord.array.push(newName);
}
return Precord;
}]);
How can an array in single factory be accessed by different controllers but one at a time such that any update in one controller must not reflect in other controllers? the precord.array is being used in all the controllers, but i want it to be isolated from other controllers while one controller is in use of it
After reviewing your code I found that you should keep a copy of array on controller level so that, If one controller update it then it will not reflect in other controllers,
I have modified your one controller and your factory, so try to implement it in other controllers also.
Try this
FCtrl
var app=angular.module('myApp',[]);
app.controller('FCtrl',['$scope','mockFactory',function($scope,mockFactory){
$scope.fCtrlJSON = [];
$scope.showPerson = function(){
mockFactory.fetchJson($scope.valueJson)
.then(function(){
$scope.persons = mockFactory.array;
$scope.fCtrlJSON = mockFactory.array;
})
}
$scope.delPerson = function(i){
mockFactory.delete($scope.fCtrlJSON,i);
}
$scope.addNamePerson = function() {
mockFactory.ADD($scope.fCtrlJSON,$scope.valueFirst);
};
$scope.showConsolePerson= function(){
console.log(JSON.stringify($scope.fCtrlJSON));
}
}]);
mockFactory
app.factory('mockFactory',['$http',function($http){
var Precord = {};
Precord.array = [];
Precord.assign = function (value) {
return $http.get('http://localhost:3000/scripts/' + value + '.json');
};
Precord.fetchJson = function(value){
return Precord.assign(value).success(function(response){
Precord.array = response.value;
})
}
Precord.delete = function(arrayData, i){
arrayData.splice(i,1);
}
Precord.ADD = function(arrayData, value){
var newName = {
Name: value
};
arrayData.push(newName);
}
return Precord;
}]);
Hi I do not understand why always I get empty array from this service when is invoked by my controller
angular
.module('dimecuba.services', [])
.factory('Contacts', function($cordovaContacts, $ionicPlatform) {
var contactsFound = [];
var contacts = {
all:function(){
var options = {};
options.multiple = true;
options.filter = "";
//options.fields = ['displayName'];
options.hasPhoneNumber = true;
$ionicPlatform.ready(function(){
$cordovaContacts.find(options).then(
function(allContacts){
angular.forEach(allContacts, function(contact, key) {
contactsFound.push(contact);
});
console.log("Contacts Found:" + JSON.stringify(contactsFound));
return contactsFound;
},
function(contactError){
console.log('Error');
}
);
});
}
}; //end contacts
console.log("Contacts:"+JSON.stringify(contacts));
return contacts;
});
Use return to chain promises. A return statement needs to be included at each level of nesting.
app.factory('Contacts', function($cordovaContacts, $ionicPlatform) {
var contacts = {
all:function(){
var options = {};
options.multiple = true;
options.filter = "";
options.hasPhoneNumber = true;
//return promise
return $ionicPlatform.ready().then(function() {
//return promise to chain
return $cordovaContacts.find(options)
}).then(function(allContacts){
var contactsFound = [];
angular.forEach(allContacts, function(contact, key) {
contactsFound.push(contact);
});
//return to chain data
return contactsFound;
}).catch(function(contactError){
console.log('Error');
//throw to chain error
throw contactError;
});
}
}; //end contacts
return contacts;
});
In the controller, use the promise returned.
app.controller("myCtrl", function($scope,Contacts) {
var contactsPromise = Contacts.all();
contactsPromise.then( function(contactsFound) {
$scope.contactsFound = contactsFound;
});
});
I'm writing a management system for an ecommerce system. The app needs to create pricing rules on a per product/ per category basis.
SO ..... For a new price rule that has a CategoryID, I want to update all products with that CategoryId. How do I call all the Products from the pricing controller and then update them?
I want this function in the Pricing's controller to update Products with a CategoryId that was set in the form.
$scope.saveRule = function saveRule(row){
var CategoryId = row.CategoryId;
if(row.id =="newRecord"){
var roundup = $('#roundupnewRecord').val();
var percentage = $('#percentagenewRecord').val();
var pricing = new Pricing({
CategoryId: CategoryId,
roundup: roundup,
percentage: percentage
});
pricing.$save(function(response) {
$route.reload();
});
} else {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.roundup = $('#roundup'+row.id).val();
pricing.percentage = $('#percentage'+row.id).val();
pricing.$update(function() {
$route.reload();
});
});
}
}
Thanks in advance for any help.
Pricing Controller. - angular
'use strict';
angular.module('mean.pricing').controller('PricingController', [ '$route', '$http', '$scope', '$routeParams', '$location', 'Global', 'Pricing', function ($route, $http, $scope, $routeParams, $location, Global, Pricing) {
$scope.global = Global;
$scope.create = function() {
var pricing = new Pricing({
CategoryId: this.title,
content: this.content
});
pricing.$save(function(response) {
console.log(response);
$location.path('pricing/' + response.id);
});
this.title = '';
this.content = '';
};
function generateDefaultRule() {
return {
CategoryId: 0,
ProductId: '',
roundup: 2,
percentage: 1,
newRecord: 1,
id: 'newRecord'
}
}
$scope.addRule = function addRule(id) {
$scope.rowCollection.push(generateDefaultRule());
console.log();
};
$scope.saveRule = function saveRule(row){
var CategoryId = row.CategoryId;
if(row.id =="newRecord"){
var roundup = $('#roundupnewRecord').val();
var percentage = $('#percentagenewRecord').val();
var pricing = new Pricing({
CategoryId: CategoryId,
roundup: roundup,
percentage: percentage
});
pricing.$save(function(response) {
$route.reload();
});
} else {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.roundup = $('#roundup'+row.id).val();
pricing.percentage = $('#percentage'+row.id).val();
pricing.$update(function() {
$route.reload();
});
});
}
//Get Products with Relative CategoryId
}
$scope.update = function() {
var pricing = $scope.pricing;
if (!pricing.updated) {
pricing.updated = [];
}
pricing.updated.push(new Date().getTime());
pricing.$update(function() {
$location.path('pricing/' + pricing.id);
});
};
$scope.find = function() {
Pricing.query(function(pricing) {
$scope.pricing = pricing;
});
};
$scope.findOverall = function() {
$http.get('/Pricing/overall').then(function(pricing) {
$scope.overall = pricing;
});
};
$scope.findCategories = function() {
$http.get('/Pricing/categories').then(function(pricing) {
console.log(pricing);
$scope.categories = pricing.data;
});
};
$scope.findProducts = function() {
$http.get('/Pricing/products').then(function(pricing) {
$scope.products = pricing.data;
});
};
$scope.findOne = function() {
Pricing.get({
pricingId: $routeParams.pricingId
}, function(pricing) {
$scope.pricing = pricing;
});
};
$scope.remove = function(pricing) {
if (pricing) {
pricing.$remove();
for (var i in $scope.pricing) {
if ($scope.pricing[i] === pricing) {
$scope.pricing.splice(i, 1);
}
}
}
else {
$scope.pricing.$remove();
$location.path('pricing');
}
};
$scope.removeItem = function removeItem(row) {
Pricing.get({
pricingId: row.id
}, function(pricing) {
pricing.$remove(function() {
var index = $scope.rowCollection.indexOf(row);
if (index !== -1) {
$scope.rowCollection.splice(index, 1);
}
});
});
}
$scope.list = function(){
$('table').on('click', 'a' , function (event) {
var id = $(this).attr('id');
if($(this).hasClass('editButton')){
$('#percentage'+id).css('display','inline-block');
$('#roundup'+id).css('display','inline-block');
$('#percentageSpan'+id).css('display','none');
$('#roundupSpan'+id).css('display','none');
$('.actionButtonsDiv'+id).css('display','none');
$('#saveButtonDiv'+id).css('display','inline');
}
});
$http.get('/pricing').then(function(pricing) {
$scope.rowCollection = pricing.data;
});
$http.get('/category').then(function(categories) {
$scope.categories = categories.data;
});
}
}]);
Products Controller - angular
'use strict';
angular.module('mean.products').controller('ProductsController', ['$http', '$scope', '$routeParams', '$location', 'Global', 'Products', function ($http, $scope, $routeParams, $location, Global, Products) {
$scope.global = Global;
$scope.create = function() {
var product = new Products({
title: this.title,
content: this.content
});
product.$save(function(response) {
$location.path("products/" + response.id);
});
this.title = "";
this.content = "";
};
$scope.remove = function(product) {
if (product) {
product.$remove();
for (var i in $scope.products) {
if ($scope.products[i] === product) {
$scope.products.splice(i, 1);
}
}
}
else {
$scope.product.$remove();
$location.path('products');
}
};
$scope.update = function() {
var product = $scope.product;
if (!product.updated) {
product.updated = [];
}
product.updated.push(new Date().getTime());
product.$update(function() {
$location.path('products/' + product.id);
});
};
$scope.find = function() {
Products.query(function(products) {
// console.log(products);
$scope.products = products;
});
};
$scope.categories = function() {
var selected = {};
$('#multiple').on('click', function(){
$('.product-checkbox').each(function() {
if ($(this).is(":checked")) {
$(this).prop('checked', false);
}else{
$(this).prop('checked', true);
}
});
});
$.each( ['approveButton', 'rejectButton', 'multiButton'], function( index, value ){
$('.'+value).on('click', function(){
$('.product-checkbox').each(function() {
var productId = $(this).attr('id');
if ($(this).is(":checked")) {
if (value === 'rejectButton') {
var categoryId = 199;
}else{
var categoryId = $('#selectProduct'+$(this).attr('id')).val().replace('number:','');
}
Products.get({
productId: productId
}, function(product){
product.CategoryId = categoryId;
product.$update(function(result) {
});
});
}
//Approves checked and rejcts unchecked products
if (value == 'multiButton') {
if (!$(this).is(":checked")) {
Products.get({
productId: productId
}, function(product){
product.CategoryId = 199;
product.$update(function() {
});
});
}
}
});
$location.path('products/categories');
});
});
$http.get('/products/categories').then(function(products) {
$scope.products = products.data;
});
$http.get('/category').then(function(categories) {
$scope.categories = categories.data;
});
$http.get('/productCategoryMatchs').then(function(productCategoryMatchs) {
var pCMResponse = productCategoryMatchs.data;
var pcmArray = {};
for(var index in pCMResponse){
pcmArray[pCMResponse[index].ProductId] = pCMResponse[index].CategoryId;
}
$scope.pCMs = pcmArray;
});
};
$scope.findOne = function() {
Products.get({
productId: $routeParams.productId
}, function(product) {
$scope.product = product;
});
};
}]);
Products Controller -node
'use strict';
/**
* Module dependencies.
*/
var StandardError = require('standard-error');
var db = require('../../config/sequelize');
/**
* Find product by id
* Note: This is called every time that the parameter :productId is used in a URL.
* Its purpose is to preload the product on the req object then call the next function.
*/
exports.product = function(req, res, next, id) {
console.log('id => ' + id);
db.Product.find({ where: {id: id}}).then(function(product){
if(!product) {
return next(new Error('Failed to load product ' + id));
} else {
req.product = product;
return next();
}
}).catch(function(err){
return next(err);
});
};
/**
* Create a product
*/
exports.create = function(req, res) {
// augment the product by adding the UserId
req.body.UserId = req.user.id;
// save and return and instance of product on the res object.
db.Product.create(req.body).then(function(product){
if(!product){
return res.send('users/signup', {errors: new StandardError('Product could not be created')});
} else {
return res.jsonp(product);
}
}).catch(function(err){
return res.send('users/signup', {
errors: err,
status: 500
});
});
};
/**
* Update a product
*/
exports.update = function(req, res) {
// create a new variable to hold the product that was placed on the req object.
var product = req.product;
product.updateAttributes({
price: req.body.price,
CategoryId: req.body.CategoryId
}).then(function(a){
return res.jsonp(a);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* Delete an product
*/
exports.destroy = function(req, res) {
// create a new variable to hold the product that was placed on the req object.
var product = req.product;
product.destroy().then(function(){
return res.jsonp(product);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* Show an product
*/
exports.show = function(req, res) {
// Sending down the product that was just preloaded by the products.product function
// and saves product on the req object.
return res.jsonp(req.product);
};
/**
* List of Products
*/
exports.all = function(req, res) {
db.Product.findAll({}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render('error', {
error: err,
status: 500
});
});
};
/**
* List of Products
*/
exports.list = function(req, res) {
db.Product.findAll({
limit : 20
}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render('500', {
error: err,
status: 500
});
});
};
/**
* List of Products and there categories
*/
exports.categories = function(req, res) {
db.Product.findAll({
attributes : [
'name',
'id',
// 'ProductCategoryMatch.count'
],
where: {
CategoryId : null
},
// include : [
// { model: db.ProductCategoryMatch }
// ],
// order : [
// ]
limit: 20
}).then(function(products){
return res.jsonp(products);
}).catch(function(err){
return res.render(500, {
error: err,
status: 500
});
});
};
/**
* Article authorizations routing middleware
*/
exports.hasAuthorization = function(req, res, next) {
// if (req.product.User.id !== req.user.id) {
// return res.send(401, 'User is not authorized');
// }
next();
};
I am trying to create an infinite scroll based on Gajotres post (http://www.gajotres.net/ionic-framework-tutorial-11-infinite-scroll/)
My problems are:
If i write : $scope.searchObjects($scope.formData); all $scope objects are printed on the screen, how can it be avoided?
Can i pass form data by using $scope.formData, this way: .
$scope.searchObjects($scope.formData);
Until now the list freezes with 7000 itens and can not get the infinite scroll to work , seems it load all the itens.
There is a better know solution to ionic infinite scroll with http.post ?
Here is my attempt code any help would be apreciated :
.controller('someObjectsCtrl', function( $scope, $http) {
$scope.data = null;
$scope.itens = [];
$scope.data = {
'state' : '',
'city' : '',
}
$http.get('http://someservice.com/states.php').then( function response(response){
$scope.states = response.data;
},function(error){
$scope.error = JSON.stringfy(error);
});
$scope.getCities = function(id) {
$http.get('http://someservice.com/state.php?stateid='+id).then( function response(result) {
$scope.cities = result.data;
$ionicLoading.hide();
},function(error) {
$scope.error = JSON.stringfy(error);
});
};
$scope.originForm = angular.copy($scope.data);
$scope.searchObjects = function(data) {
$scope.formData = {};
$scope.formData.state = data.state;
$scope.formData.city = data.city;
$http.post("http://someservice.com/objectsToSearch.php", $scope.formData )
.success( function(data) {
$scope.result = data;
for (var i = 0; i <= 6; i++) {
$scope.itens.push({ foundObjects: $scope.result.OBJECTS});
}
$scope.$broadcast('scroll.infiniteScrollComplete');
if( $scope.result.length == 0 ){
$scope.data = null;
}
$scope.headers = ['Some Objects', 'Another Objects' ];
})
.error(function(error){
$ionicLoading.show({ template: '<p>Error ...</p>',duration :6000 });
})
}
$scope.canWeLoadMoreContent = function() {
return ($scope.itens.length > 10) ? false : true;
console.log(' scope.itens.length '+$scope.itens.length );
}
$scope.searchObjects($scope.formData);
})
Until now the only solution i find was to use collectio-repeat instead of ng-repeat. Collection-repeat is very fast rendering the result list.