angularFire unable to $add data to firebase - javascript

I am using angularFire and trying to save data from a form to firebase with $add. Any help would be greatly appreciated. The console logs all work, I am able to retrieve the data in the console. Sorry for all of the code... I wanted to be sure I provided all the material needed.
app.js:
var creativeBillingApp = angular.module('creativeBillingApp', ['ngRoute', 'firebase']);
creativeBillingApp.constant('FIREBASE_URI', "https://XXXX.firebaseIO.com/");
creativeBillingApp.controller('MainCtrl', ['$scope', 'groupsService', function( $scope, groupsService, $firebase ) {
console.log('Works')
$scope.newGroup = {
name: '',
status: ''
};
$scope.addGroup = function(newGroup){
console.log(newGroup);
groupsService.addGroup();
$scope.newGroup = {
name: '',
status: ''
};
};
$scope.updateGroup = function (id) {
groupsService.updateGroup(id);
};
$scope.removeGroup = function(id) {
groupsService.removeGroup(id);
};
}]);
creativeBillingApp.factory('groupsService', ['$firebase', 'FIREBASE_URI',
function ($firebase, FIREBASE_URI) {
'use strict';
var ref = new Firebase(FIREBASE_URI);
return $firebase(ref).$asArray();
var groups = $firebase(ref).$asArray();
var getGroups = function(){
return groups;
};
var addGroup = function (newGroup) {
console.log(newGroup)
groups.$add(newGroup);
};
var updateGroup = function (id){
groups.$save(id);
};
var removeGroup = function (id) {
groups.$remove(id);
};
return {
getGroups: getGroups,
addGroup: addGroup,
updateGroup: updateGroup,
removeGroup: removeGroup,
}
}]);
index.html:
<form role="form" ng-submit="addGroup(newGroup)">
<div class="form-group">
<label for="groupName">Group Name</label>
<input type="text" class="form-control" id="groupName" ng-model="newGroup.name">
</div>
<div class="form-group">
<label for="groupStatus">Group Status</label>
<select class="form-control" ng-model="newGroup.status">
<option value="inactive">Inactive</option>
<option value="active">Active</option>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
This is the error I am getting:
TypeError: undefined is not a function
at Scope.$scope.addGroup (http://localhost:9000/scripts/app.js:35:19)
and the app.js line 35 is in reference to groupsService.addGroup(); from the app.js code given above.

Firstly, you are returning in your service after you create your $FirebaseArray. You are also creating another $FirebaseArray after that.
return $firebase(ref).$asArray();
Remove that return statement. That is causing your service to return early and none of the attached methods will apply to your service.
In groupService.addGroup() you are calling push, which is not a function on $asArray. You need to call .$add(). The newGroup argument is also not being passed in the controller.
The $.push method is available on the base of the $firebase binding. When you using a $FirebaseArray the $add method pushes a new record into Firebase.
See the docs for more info.
Plunker Demo
var addGroup = function (newGroup) {
console.log(newGroup)
groups.$add(newGroup);
};
Then in your controller you can simply call:
$scope.addGroup = function(newGroup){
groupsService.addGroup(newGroup);
$scope.newGroup = {
name: '',
status: ''
};
};

Related

Storing HTML form input in a JS object

I know there is a very similar question asked over here but my object hierarchy is different than the one in that question.
Anyways, I want to store the HTML form input data in to my JavaScript object. Here is my HTML form code:
<form id="newAuction">
<input id="title" name="title" required type="text" value="" />
<input id="edate" name="edate" required type="datetime" value="" />
<input id="minbid" name="minbid" required type="number" value="" />
<button class="btn btn-primary">Submit</button>
</form>
What I want is to get the values of these 3 inputs and store it in my JS object.
I know the proper JSON format needed to post the data to my API. (I tried POSTing with POSTman and I get a status 200, so it works). The proper format is:
{
"auction": {
"Title": "Auction1",
"EDate": "01/01/1990",
"MinBid": 30
},
"productIds": [1,2,3]
}
This is what my JS object looks like:
<script>
$(document).ready(function() {
var vm = {
auction: {},
productIds: []
};
//validation and posting to api
var validator = $("#newAuction").validate({
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
submitHandler: function () {
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});
});
</script>
As you can see, I am using document.getElementById('title').value; to get the values and assign them but I'm getting the syntax error Expected : Comma expected
Not sure if this matters, but this is inside a .NET MVC5 project.
Move your value assignment set of codes inside submitHandler. Check the syntax of validate() https://jqueryvalidation.org/validate/
//validation and posting to api
var validator = $("#newAuction").validate({
submitHandler: function () {
//assigning values
vm.auction.Title = document.getElementById('title').value;
vm.auction.MinBid = document.getElementById('minbid').value;
vm.auction.EDate = document.getElementById('edate').value;
vm.productIds.push(1);
$.ajax({
url: "/api/newAuction",
method: "post",
data: vm
})
.done(function () {
toastr.success("Auction Added to the db");
//setting the vm to a new vm to get rid of the old values
var vm = { auction: {}, productIds: [] };
validator.resetForm();
})
.fail(function () {
toastr.error("something wrong");
});
return false;
}
});

AngularJS scope values undefined but API is working fine

I don't get any error message, but while debugging Scope values are not binding it shows Undefined...
Controller:
$scope.companyModify = function () {
var param = {
companyId:$scope.companyId,
companyName:$scope.companyName,
billPrintLinesTop:$scope.billPrintLinesTop,
billPrintLinesBottom:$scope.billPrintLinesBottom,
isPrintHeader:$scope.isprintHeader,
billTypeId:$scope.billTypeId,
billColumnId :$scope.billColumnId,
noOfCopies: $scope.noOfCopies,
billHeaderAlignmentId: $scope.billHeaderAlignmentId,
billTitle: $scope.billTitle,
billSortOrderId:$scope.billSortOrderId,
posDefaultQty:$scope.posDefaultQty,
posTaxTypeId:$scope.posTaxTypeId,
isAllowNegativeStock:$scope.isAllowNegativeStock,
serviceTaxCalcTypeId : $scope.serviceTaxCalcTypeId,
wishMessage:$scope.wishMessage,
coinageBy:$scope.coinageBy,
isAutoGenerateProductCode:$scope.isAutoGenerateProductCode
};
console.log(param);
Calling the companyModify Function :
Open braces of companyModify closes in SocketService...
SocketService.post(apiManage.apiList['CompanyModify'].api,param).
then(function (resp) {
var data = resp.data.response;
if (data.status === true) {
angular.forEach($scope.companyList, function (value) {
if (value.companyId == $scope.companyId) {
value.$edit = false;
}
});
Notify.alert(data.message, {
status: 'success',
pos: 'top-right',
timeout: 5000
});
$scope.load();
}
else {
Notify.alert(data.message, {
status: 'danger',
pos: 'top-right',
timeout: 5000
});
}
});
};
Ensure $scope is properly injected in controller
someModule.controller('MyController', ['$scope', function($scope) {
...
$scope.aMethod = function() {
...
}
...
}]);
In your html code, input values are binded to company.XXX :
<input type="text" class="form-control input-sm" ng-model="company.posTaxTypeId" placeholder="Enter POSTaxCalculation" >
If you want your code to work is the controller, you must use the same binding and use posTaxTypeId: $scope.company.posTaxTypeId instead of posTaxTypeId: $scope.posTaxTypeId
or change your html code to :
<span data-ng-show="!company.isEdit" data-ng-bind="posTaxTypeId"></span>
<span data-ng-show="company.isEdit">
<input type="text" class="form-control input-sm" ng-model="posTaxTypeId" placeholder="Enter POSTaxCalculation" >
</span>
also ensure that binding are declared properly, without spaces :
bad
data-ng-bind="company.posTaxTypeId "
ng-model="company.posTaxTypeId "
good
data-ng-bind="company.posTaxTypeId"
ng-model="company.posTaxTypeId"

Edit MEANJS list in the list page

I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource

Don't have access to attribute in my controller Angular.js 1.3

I'm building a simple form.
This form get a birthday field.
I can select a date and persist it.
But when I reload the page, I have an error
Error: [ngModel:datefmt] Expected `2015-03-06T23:00:00.000Z` to be a date
I know how to resolve it. I need to convert my user.date_birthday to a Date.
So I tried this.
'use strict';
angular.module('TheNameApp')
.controller('SettingsCtrl', function ($scope, User, Auth) {
$scope.user = User.get();
$scope.errors = {};
console.log($scope.user); // display the resource
console.log($scope.user.date_birthday); //undefined
$scope.changeInformations = function(form) {
$scope.infos_submitted = true;
if(form.$valid) {
Auth.changeInformations({
gender: $scope.user.gender,
city: $scope.user.city,
country: $scope.user.country,
talent: $scope.user.talent,
date_birthday: $scope.user.date_birthday,
user_name: $scope.user.user_name,
email: $scope.user.email })
.then( function() {
$scope.infos_message = 'Done.'
})
.catch( function(err) {
err = err.data;
$scope.errors = {};
// Update validity of form fields that match the mongoose errors
angular.forEach(err.errors, function(error, field) {
form[field].$setValidity('mongoose', false);
$scope.errors[field] = error.message;
});
});
}
};
the .html
<div class="form-group">
<label>Birthday</label>
<input type="date" name="date_birthday" class="form-control" ng-model="user.date_birthday"/>
</div>
The user.date_birthday is not defined but I can see it in $scope.user
I need this for my next step
$scope.user.date_birthday = new Date($scope.user.date_birthday);
Why I can't see my attribute? How Can I resolve this?
Assuming your User is a resource, .get() is an async call. Use a callback:
User.get(function(user) {
user.date_birthday = new Date(user.date_birthday);
$scope.user = user;
});

AngularJS: Taking old values instead of new during put

When updating, I want to insert new values coming from the ui instead of old values present in the local collection. The below code inserts old values in local collection(I don't want this to happen).
dataService.getSupplierById($routeParams.id)
.then(function (supplier) {
$scope.supplier = supplier; //now this contains local collection
$scope.save = function () {
$scope.updatedSupplier = $scope.supplier; //I want the scope to be updated and take values from the ui
dataService.updateSupplier($routeParams.id, $scope.updatedSupplier)
.then(function () {
//success
},
function () {
//error
});
};
},
function () {
//error
});
This is my Html.
<div>
<label for="City">City</label>
<input name="City" type="text" data-ng-model="updateSupplier.city" value="{{supplier.city}}" />
</div>
How can I do this? How can I update the scope to take new values? I'm new to angular.
If you are binding to updateSupplier as the ng-model then you shouldn't overwrite the values when you save:
$scope.save = function () {
// remove the line that overwrites, was here
dataService.updateSupplier($routeParams.id, $scope.updatedSupplier)
.then(function () {
//success
},
function () {
//error
});
};
}
Angular will take care of two-way binding the value inside the ng-model so by the time you save it will have the correct value that was input in the textbox.
You can also clean up the code by not have 2 different scope properties:
dataService.getSupplierById($routeParams.id)
.then(function (supplier) {
$scope.supplier = supplier; //now this contains local collection
$scope.save = function () {
dataService.updateSupplier($routeParams.id, $scope.supplier )
.then(function () {
//success
},
function () {
//error
});
};
},
function () {
//error
});
And then in the html:
<div>
<label for="City">City</label>
<input name="City" type="text" data-ng-model="supplier.city" />
</div>
The initial value should bind into the value attribute automatically.

Categories

Resources