How does AngularFire $save function work? - angularjs

I want to update a group of fields based on the contract number input in, user can choose which field they want to change, and can set the value. my code does not change the record, I don't know why.I guess the reason might be the prop is not defined. The app is build on using the api of AngularFire, my code is as follows:
<div class="container-fluid">
<div class="row">
<h3>Contract renewal & Group update other fields</h3>
<form class="form-horizontal" ng-submit="groupUpdate()" name="contractupdateForm">
<div class="form-group">
<label for="washroom" class="col-sm-2 control-label"> Contract Number</label>
<div class="col-sm-8">
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter contract number so related fileds could be group updated" ng-model="contractupdate" ng-required="true">
</div>
</div>
</div>
<div class="form-group">
<label for="washroom" class="col-sm-2 control-label"> Fields Category</label>
<div class="col-sm-8">
<div class="input-group">
<select class="form-control" id="productfield" name = "productfield" ng-model="fieldupdate" ng-options="f.value as f.label for f in fields">
<option value="">No filed selected</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="washroom" class="col-sm-2 control-label"> Updated value</label>
<div class="col-sm-8">
<div class="input-group">
<input type="text" class="form-control" placeholder="Enter value supposed to be changed" ng-model="valueupdate" ng-required="true">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2">
<button type="submit" class="btn btn-default" >
Change group value
</button>
</div>
</div>
</form>
<hr>
</div>
</div>
The controller part is as follows:
$scope.groupUpdate = function(){
console.log($scope.contractupdate);
console.log($scope.fieldupdate);
console.log($scope.valueupdate);
for(var i = 0; i< productsInfo.length;i++){
if(productsInfo[i].productcontract == $scope.contractupdate){
var prop = $scope.fieldupdate;
productsInfo[i].prop = $scope.valueupdate;
productsInfo.$save(i).then(function(ref) {
console.log("group update success");
}, function(error) {
console.log("Error:", error);
});
}
/*if(i.productcontract == $scope.contractupdate){
var field = $scope.fieldupdate;
console.log(productsInfo[i].field);
productsList[i].field == $scope.valueupdate;
productsList.$save().then(function(productRef){
console.log("group updated success");
ref.key === obj.$id; // true
}, function(error) {
console.log("Error:", error);
});
}*/
};
};

The second $save operation needs to be chained from the promise returned from the first $save operation:
var promise = productsInfo.$save().then(function(ref) {
console.log("group update success");
//return to chain ref
return ref;
}, function(error) {
console.log("Error:", error);
//throw to chain error
throw error;
});
var p2 = promise.then(function(ref) {
//do more here
//return to chain promise
return productsInfo.$save();
}).catch(function(error) {
console.log("Error:", error);
//throw to chain error
throw error;
});
var p3 = p2.then(function(secondRef) {
//do even more
When code is put in a function given to a .then method, the $q service waits for the promise to resolves before invoking that function. The .then method returns a derived promise which can be used for further chaining.
For more information, see AngularJS $q Service API Reference -- chaining promises

Related

Get form input value from angularjs

I'm using Angularjs to submit the form then pass the value to my laravel function.
This is my HTML code
<form class="form-horizontal" method="post" name='form' novalidate ng-submit="submit()" ng-controller="syncApiCtrl">
<div class="col-lg-10">
<div class="input-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Your_name">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<input type="submit" name="sale" value="Sync Sale" class="btn btn-primary"></input>
<input type="submit" novalidate ng-click="sync_product(record)" name="product" value="Sync Product" class="btn btn-primary"></input>
</div>
</div>
</form>
This is my JS
$scope.submit = function () {
//$scope.form.$submitted = true;
// proceed if form valid
if ($scope.form.$valid) {
// is loading
$scope.loading = true;
// prepare data packet
var data = {};
angular.forEach($scope.form, function (v, k) {
if (k.indexOf('$') < 0 && typeof v.$dirty !== 'undefined' && v.$dirty) {
data[k] = v.$modelValue;
}
});
}
};
This is my laravel function
public function sync_sale() {
$name= preg_replace('/[^A-Za-z0-9\_]/', '', Input::get('name'));
Debugbar::info($name);
}
My laravel function always can't get the value after user submit a form.
You should have bound your input to a ng-model. This one is working. You should use data binding methods in angularJs.
<input type="text" class="form-control" id="name" name="name" placeholder="Your_name" ng-model="name">

AngularJS - Create dynamic email fields and checking and validation

I would like to create a form with several fields: name, last name, ... and add one or several email. The first email field is mandatory. After he should have the possibility to click on "Add email" for adding a new email address. He could add 4 others emails (5 emails in total).
The system should be verify if the format of the email is correct, display a message if necessary and register the data in a DB.
Here my controler "ctrlAddContacts" and module (app.js):
var app=angular.module('ContactsApp', ['ngRoute', 'ui.bootstrap', 'ngDialog']);
app.factory('HttpInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
return {
// On request success
request : function(config) {
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
// On request failure
requestError : function(rejection) {
//console.log(rejection); // Contains the data about the error on the request.
// Return the promise rejection.
return $q.reject(rejection);
},
// On response success
response : function(response) {
//console.log(response); // Contains the data from the response.
// Return the response or promise.
return response || $q.when(response);
},
// On response failure
responseError : function(rejection) {
//console.log(rejection); // Contains the data about the error.
//Check whether the intercept param is set in the config array.
//If the intercept param is missing or set to true, we display a modal containing the error
if (typeof rejection.config.intercept === 'undefined' || rejection.config.intercept)
{
//emitting an event to draw a modal using angular bootstrap
$rootScope.$emit('errorModal', rejection.data);
}
// Return the promise rejection.
return $q.reject(rejection);
}
};
app.controller('ctrlAddContacts', function ($scope, ContactService){
$scope.title="Add a contact";
// Allow to create several fields EMAIL
$scope.emails = [
{
}];
$scope.log = function() {
console.log($scope.emails);
};
$scope.add = function() {
var dataObj = {email:''};
$scope.emails.push(dataObj);
}
$scope.submitForm = function(contact){
if($scope.ContactForm.$valid){
// Send the object to the backend for saving data
ContactService.addNewPerson(contact).success(function(Person){
$scope.ContactForm.$setPristine();
$scope.contact= Person;
});
}
}
});
Here my factory (appService.js)
app.factory('ContactService', function($http){
var factory={};
factory.addNewPerson=function(objContact){
//alert(objContact);
return $http.get('http://myapp/contacts.cfc?method=addNewPerson&jsStruct=' + JSON.stringify(objContact))
};
return factory;
})
The function in the backend (server) retrieves the parameter objContact sent by the backend and executes correctly the query (it's working)
Here my view (manageContact.html)
<h3>{{title}}</h3>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">Person Sheet</div>
</div>
<div class="panel-body">
<form name="ContactForm" class="form-horizontal" role="form" novalidate ng-submit="submitForm(contact)">
<div class="form-group">
<label for="txtLastName" class="col-sm-2 control-label">Last Name *</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="txtLastName" maxlength="100" placeholder="Enter Last Name" required ng-model="contact.LASTNAME">
</div>
</div>
<div class="form-group">
<label for="txtPhone" class="col-sm-2 control-label">Phone Number</label>
<div class="col-sm-10">
<input type="number" class="form-control" name="txtPhone" maxlength="20" placeholder="Enter phone" ng-model="contact.PHONENUMBER">
</div>
</div>
<!---------------- FOR ADDING EMAILS FIELDS ------------ START --->
<div>
<div ng-repeat="email in emails">
<div class="form-group">
<label for="txtEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" name="txtEmail_" maxlength="100" placeholder="Enter Email" ng-model="contact.EMAIL">
</div>
</div>
</div>
<button ng-click="add()">Add Email</button>
</div>
<!---------------- FOR ADDING EMAILS FIELDS ------------ END--->
<div class="error-container"
ng-show="ContactForm.txtEmail.$dirty && ContactForm.txtEmail.$invalid">
<small class="error"
ng-show="ContactForm.txtEmail.$error.required">
Your email is required.
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.minlength">
Your email is required to be at least 3 characters
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.email">
That is not a valid email. Please input a valid email.
</small>
<small class="error"
ng-show="ContactForm.txtEmail.$error.maxlength">
Your email cannot be longer than 20 characters
</small>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-primary" value="Submit" ng-disabled="ContactForm.$invalid">
Cancel
</div>
</div>
</form>
</div>
</div>
Could you please help me for doing the difference in the name of the 5 fields: txtEmail_1, txtEmail_2 in the controler and the view (when the new field is created).
Kind Regards,
You could try the following for creating dynamic form element name attributes.
<div class="col-sm-10">
<input type="email" class="form-control"
name="txtEmail_{{$index}}" maxlength="100"
placeholder="Enter Email" ng-model="contact.EMAIL">
</div>
<span ng-show="ContactForm['txtEmail_' + $index].$invalid">Enter a valid email</span>

angular post is sending null value to server

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.submitForm = function(cl) {
console.log(cl);
$http({
method: 'POST',
url: "updated-profile",
data: {
cl: cl
},
}).then(function successCallback(response) {
console.log("updated successfully");
$scope.success = "Updated successfully";
}, function errorCallback(response) {
console.log("not updated");
$scope.error = "Unable to update";
});
}
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="cl in clientList">
<div id="error-messages" ng-show="error">{{error}}</div>
<div id="success" ng-show="success">{{success}}</div>
<div class="form-group">
<div class="col-lg-4 col-md-4">
<label for="fname">First Name</label>
</div>
<div class="col-lg-8 col-md-8 ">
<input type="text" class="form-control" placeholder="First Name" ng-model="cl.fname" />
</div>
</div>
<div class="form-group">
<div class="col-lg-4 col-md-4">
<label for="lname">Last Name</label>
</div>
<div class="col-lg-8 col-md-8">
<input type="text " class="form-control" ng-model="cl.lname" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-4 col-md-4">
<label for="submit" class="sr-only">Update</label>
</div>
<div class="col-lg-8 col-md-8">
<input type="button" class="form-control btn btn-success" id="update" ng-click="submitForm(cl)" name="Update" value="Update" />
</div>
</div>
</div>
I am using above code to send data to server.
My server code is
public class Update extends ActionSupport {
private Client cl = new Client();
private String fname;
public String update() {
System.out.println("testing this");
System.out.println("client detail " + cl.getFname() + " " +
cl.getLname());
System.out.println("fname"+getFname());
}
}
I am getting
client detail null null
fnamenull
If I am using data: {fname: cl.fname}, then also fnamenull.
I am unable to pass any value using angular post to action.
What is wrong here?
What changes to made here to work it properly?
Your button
<input type="button" class="form-control btn btn-success" id="update" ng-click="submitForm(cl)" name="Update" value="Update" />
has to be inside the ng-repeat loop, otherwise it will not have access to the cl object as that is local to the ng-repeat scope.
Alternatively, if you want the button to be "global", you can submit the entire clientList in the ng-submit and then loop through the array inside your controller. It depends on your flow and what kind of UX/UI you need for the project.
$http({
method: 'POST',
url: "www.mylocalhost.com/api/updated-profile",
data: {
cl: cl
},
});
When you are calling a $http service "url" parameter shoul contain a proper api path. just use a valid api url . I hope it will work.
Or
change "cl":$scope.clientList

Multiple controllers in a meanjs form, submitting empty values

I am calling some values from the database and putting them in a select box in a form, however, whenever i click on submit, it submits an empty value, i am thinking its because i am using multiple controllers in the form, from what i have gathered, i have to do something with scope in the controllers, but i have been unable to do that
Attached is a copy of the create-view file, the highlited portions are the multiple controllers.
Please how do i make it work? Thank you very much
<section data-ng-controller="CandidatesController">
<div class="page-header">
<h1>New Candidate</h1>
</div>
<div class="col-md-12">
<form class="form-horizontal" data-ng-submit="create()" novalidate>
<fieldset>
<div class="form-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="vision">Vision</label>
<div class="controls">
<textarea data-ng-model="vision" id="vision" class="form-control"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label" for="dob">Date Of Birth</label>
<div class="controls">
<input type="date" data-ng-model="dob" id="dob" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="post">Post</label>
<div class="controls">
<select data-ng-model="post" id="post" class="form-control">
<option value="Presidential">PRESIDENTIAL</option>
<option value="Provincial">PROVINCIAL</option>
<option value="Municipal">MUNICIPAL</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label" for="province">Province</label>
<div class="controls">
<select data-ng-model="province" id="province" class="form-control">
<option value="Gauteng">Gauteng</option>
<option value="Free-State">Free-State</option>
<option value="Kwazulu-Natal">Kwazulu-Natal</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label" for="municipal">Municipal</label>
<div class="controls">
<input type="text" data-ng-model="municipal" id="municipal" class="form-control" placeholder="municipal" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="party">Party</label>
<div class="controls">
<section data-ng-controller="PartiesController" data-ng-init="find()">
<select data-ng-model="party" class="form-control" ng-options="party.name for party in parties track by party.name">
</select>
</section>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
The candidate controller code
'use strict';
//Candidates controller
angular.module('candidates').controller('CandidatesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Candidates',
function($scope, $stateParams, $location, Authentication, Candidates ) {
$scope.authentication = Authentication;
// Create new Candidate
$scope.create = function() {
// Create new Candidate object
var candidate = new Candidates ({
name: this.name,
vision: this.vision,
dob: this.dob,
post: this.post,
province: this.province,
municipal: this.municipal,
party: this.party
});
// Redirect after save
candidate.$save(function(response) {
$location.path('candidates/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Candidate
$scope.remove = function( candidate ) {
if ( candidate ) { candidate.$remove();
for (var i in $scope.candidates ) {
if ($scope.candidates [i] === candidate ) {
$scope.candidates.splice(i, 1);
}
}
} else {
$scope.candidate.$remove(function() {
$location.path('candidates');
});
}
};
// Update existing Candidate
$scope.update = function() {
var candidate = $scope.candidate ;
candidate.$update(function() {
$location.path('candidates/' + candidate._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Candidates
$scope.find = function() {
$scope.candidates = Candidates.query();
};
// Find existing Candidate
$scope.findOne = function() {
$scope.candidate = Candidates.get({
candidateId: $stateParams.candidateId
});
};
}
]);

How to $http.post with payload in data?

How do I post data from a form in AngularJS?
<form data-ng-submit="doSomething()">
<input type="text" data-ng-input="do_obj.text"/>
<input type="email" data-ng-input="do_obj.email"/>
<input type="submit" value="Do something"/>
</form>
$scope.doSomething = function () {
$http({url: '/api/oauth2/register', method: 'POST', data: $scope.do_obj}
).then(function (data, status, headers, config) {
$log.info("data = ", data, "status = ", status,
"headers = ", headers, "config = ", config);
}
);
};
Plnkr (bootstrap styled)
See plunker code here
Changed data-ng-input into data-ng-model and updated data-ng-submit to pass in the model into the scope controller for processing.
HTML:
<body data-ng-app>
<div data-ng-controller="DoCtrl" class="container" style="margin: 15px">
<form data-ng-submit="doSomething(do_obj)" role="form" class="form-inline">
<div class="form-group">
<input type="text" data-ng-model="do_obj.bar"
placeholder="Enter text"
/>
</div>
<div class="form-group">
<input class="form-group" type="email"
data-ng-model="do_obj.email"
placeholder="Enter email"
/>
</div>
<div class="form-group">
<input class="btn btn-lg" type="submit"
data-ng-class="{'btn-info': hover}"
data-ng-mouseenter="hover = true"
data-ng-mouseleave="hover = false"
value="Do something"
/>
</div>
</form>
</div>
</body>
The syntax for posting is $http.post({url}, {payload});. I have updated your controller function to take in a parameter to pass to the post.
Controller code:
function DoCtrl($scope, $http, $log) {
$log.info("In DoCtrl");
$scope.do_obj = {};
$scope.doSomething = function (data) {
$http.post('/api/oauth2/register', data)
.success(function(successData){
console.log(successData);
});
}
}

Resources