how to create dynamic form in angularjs? - angularjs

My error description:
step 1: I am appending template using this directive.
step 2: Now I remove this appended template using this scope function "removeMilestoneDiv".
step 3: After submit my form. But, I can't submitted.
I think I have add template then bind this scope variable. But, i have remove this template then scope variable is can't unbind.
Create directive for add milestone:
app.directive('addMilestone', ['$compile', function ($compile) { // inject $compile service as dependency
return {
restrict: 'A',
link: function (scope, element, attrs) {
// click on the button to add new input field
element.find('a').bind('click', function () {
// I'm using Angular syntax. Using jQuery will have the same effect
// Create input element
// var input = angular.element('<div id="scope.mileStoneId_'+ scope.mileStoneCounter +'" class="form">Milestone - '+scope.mileStoneCounter+'</div>');
var input = angular.element(''+
'<div class="card bg-white" id="mileStoneDiv_'+ scope.mileStoneCounter +'">'+
'<div class="card-header" ng-bind="\'project.ADD_MILESTONE\' | translate"></div>'+
''+
'<div class="card-block m-b-0">'+
'<div compile-template class="form-group">'+
'<label class="col-sm-2 control-label"><span ng-bind="\'project.COMPANY_MILESTONE_ID\' | translate"></span></label>'+
'<div class="col-sm-5">'+
'<input type="text" class="form-control" ng-model="company_milestone_id['+ scope.mileStoneCounter +']" ng-maxlength="100" name="company_milestone_id_'+ scope.mileStoneCounter +'" required>'+
'<div ng-messages="frmProjectAdd[\'company_milestone_id_'+scope.mileStoneCounter+'\'].$error" role="alert" class="help-block has-error">'+
'<span ng-message="required" class="help-block has-error">Company Milestone Id is required.</span>'+
'<span class="help-block has-error" ng-message="maxlength">Maximum 100 characters allowed!</span>'+
'</div>'+
'</div>'+
'</div>'+
'<div compile-template class="form-group">'+
'<label class="col-sm-2 control-label" ng-bind="\'project.MILESTONE_NAME\' | translate"></label>'+
'<div class="col-sm-5">'+
'<input type="text" ng-maxlength="100" class="form-control" ng-model="milestone_name['+ scope.mileStoneCounter +']" name="milestone_name_'+ scope.mileStoneCounter +'" required>'+
'<div ng-messages="frmProjectAdd[\'milestone_name_'+scope.mileStoneCounter+'\'].$error" class="has-error login-error">'+
'<span ng-message="required" class="help-block has-error">Milestone Name is required.</span>'+
'</div>'+
'</div>'+
'</div>'+
'<div compile-special-template class="form-group">'+
'<label class="col-sm-2 control-label" ng-bind="\'project.SELECT_EMPLOYEE\' | translate"></label>'+
'<div class="col-sm-10">'+
'<select style="min-width:250px;" ui-select2 name="select_new_employee_'+scope.mileStoneCounter+'" ng-model="selectEmployee['+ scope.mileStoneCounter +']" data-placeholder="Select Employee" ng-required="true" multiple>'+
'<option ng-repeat="manager in managerList" value="{{manager.id}}">{{manager.username}}</option>'+
'</select>'+
'</div>'+
'<div ng-messages="frmProjectAdd[\'select_new_employee_'+scope.mileStoneCounter+'\'].$error" class="has-error login-error">'+
'<span ng-message="required" class="help-block has-error">Employee is required.</span>'+
'</div>'+
'</div>'+
'</div>');
// Compile the HTML and assign to scope
var compile = $compile(input)(scope);
// Append input to div
$('#milestoneHtml').append(input);
// Increment the counter for the next input to be added
scope.mileStoneCounter++;
});
}
}
}]);
Remove milestone using this function:
$scope.removeMilestoneDiv = function(key, id, flag) {
var confirmVal = confirm("Are you sure you want to delete this Milestone?");
if(confirmVal) {
$('#mileStoneDiv_'+key).remove();
if(flag == 1){
if(id != 0) {
$scope.deletedMilestoneIds.push(id);
}
}
}
},

Create One Array:
$scope.mileStoneCounterNew = [{
'countId':1,
'company_milestone_id':'',
'milestone_name':'',
'milestone_start_date':'',
'milestone_end_date':'',
'milestone_completion_date':'',
'selectEmployee':'',
}];
Create one scope function
$scope.milestoneHtmlAdd = function() {
$scope.mileStoneCounter++;
var counterObj = {countId: $scope.mileStoneCounter };
$scope.mileStoneCounterNew.push(counterObj);
};
My Dynamic HTML
<!-- Add Milestone - Start -->
<div class="row" ng-repeat="(counterKey, counterValue) in mileStoneCounterNew" id="milestone_display_id_{{counterValue.countId}}">
<div class="card bg-white mt50">
<div class="card-header"><span ng-bind="'project.ADD_MILESTONE' | translate"></span></div>
<a ng-if="counterKey > 0" href="javascript:void(0)" class="removebtn glyphicon glyphicon-remove form-control-feedback" ng-click="milestoneDivRemove(counterKey,0,0)"></a>
<div class="card-block m-b">
<!--Milestone sub section-->
<!-- Company Milestone Id -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.COMPANY_MILESTONE_ID' | translate"></span></label>
<div class="col-sm-5">
<input type="text" class="form-control" ng-model="counterValue.company_milestone_id" ng-maxlength="100" name="company_milestone_id_{{counterValue.countId}}" required>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['company_milestone_id_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['company_milestone_id_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Company Milestone Id is required.</span>
<span class="help-block has-error" ng-message="maxlength">Maximum 100 characters allowed!</span>
</div>
</div>
</div>
<!-- Milestone name -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_NAME' | translate"></span></label>
<div class="col-sm-5">
<input type="text" class="form-control" ng-model="counterValue.milestone_name" ng-maxlength="100" name="milestone_name_{{counterValue.countId}}" required>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['milestone_name_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['milestone_name_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Milestone Name is required.</span>
<span class="help-block has-error" ng-message="maxlength">Maximum 100 characters allowed!</span>
</div>
</div>
</div>
<!-- Milestone Start Date -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_START_DATE' | translate"></span></label>
<div class="col-sm-3">
<div class="input-group">
<input name="milestone_start_date_{{counterValue.countId}}" type="text" uib-datepicker-popup="MM/dd/yyyy" ng-model="counterValue.milestone_start_date" is-open="dpOpened['milestone_start_date_'+counterValue.countId]" ng-click="milestone_start_date[counterValue.countId].open = true" max-date="maxDate" datepicker-options="dateOptions" close-text="Close" ng-required="true" class="form-control"
min-date="minDate" ng-change="set_min_milestone_end_Date(milestone_start_date[counterValue.countId])"
disabled>
<span class="input-group-addon" ng-click="open($event,'milestone_start_date_{{counterValue.countId}}')"><i class="fa fa-calendar"></i></span>
</div>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['milestone_start_date_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['milestone_start_date_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Milestone Start Date is required.</span>
</div>
</div>
</div>
<!-- Milestone End Date -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_END_DATE' | translate"></span></label>
<div class="col-sm-3">
<div class="input-group">
<input name="milestone_end_date_{{counterValue.countId}}" type="text" uib-datepicker-popup="MM/dd/yyyy" ng-model="counterValue.milestone_end_date" is-open="dpOpened['milestone_end_date_'+counterValue.countId]" ng-click="milestone_end_date[counterValue.countId].open = true" max-date="maxDate" datepicker-options="dateOptions" close-text="Close" ng-required="true" class="form-control"
min-date="milestone_end_minDate" ng-change="set_min_milestone_completed_Date(milestone_end_date[counterValue.countId])"
disabled>
<span class="input-group-addon" ng-click="open($event,'milestone_end_date_{{counterValue.countId}}')"><i class="fa fa-calendar"></i></span>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['milestone_end_date_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['milestone_end_date_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Milestone End Date is required.</span>
</div>
</div>
</div>
</div>
<!-- Milestone Completion Date -->
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.MILESTONE_COMPLETION_DATE' | translate"></span></label>
<div class="col-sm-3">
<div class="input-group">
<input type="text" uib-datepicker-popup="MM/dd/yyyy" ng-model="counterValue.milestone_completion_date" is-open="dpOpened['milestone_completion_date_'+counterValue.countId]" ng-click="milestone_completion_date[counterValue.countId].open = true" max-date="maxDate" datepicker-options="dateOptions" close-text="Close" class="form-control"
min-date="milestone_completed_minDate" disabled>
<span class="input-group-addon" ng-click="open($event,'milestone_completion_date_{{counterValue.countId}}')"><i class="fa fa-calendar"></i></span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><span ng-bind="'project.SELECT_EMPLOYEE' | translate"></span></label>
<div class="col-sm-10">
<select name="select_employee_{{counterValue.countId}}" ui-select2 ng-model="counterValue.selectEmployee" data-placeholder="Select Employee" ng-required="true" multiple>
<option ng-repeat="manager in managerList" value="{{manager.id}}">{{manager.username}}</option>
</select>
<div ng-if="frmProjectAdd.$submitted || frmProjectAdd['select_employee_'+counterValue.countId].$touched" ng-messages="frmProjectAdd['select_employee_'+counterValue.countId].$error" role="alert" class="help-block has-error">
<span ng-message="required" class="help-block has-error">Employee is required.</span>
</div>
</div>
</div>
<!-- Milestone sub section -->
</div>
</div>
</div>
<!-- Add Milestone End -->

Related

angularjs form data is not post properly.?

My HTML form data is not POST
HTML View Page:-
<div class="col-sm-12">
<div class="card-box">
<form class="form-inline" name="addstock"
ng-submit="saveStockPurchaseInvoice()">
<h3 class="m-t-0 m-b-30 header-title text-center">Invoice
Details</h3>
<div class="row" style="margin-bottom: 20px;">
<div class="form-group col-md-3" style="">
<select name="supplier" ng-model="productStock.suppliername"
class="form-control" required="">
<option value="">Select a Supplier</option>
<option ng-repeat="allsupplier in supplier"
value="{{allsupplier.supplier_id}}">
{{allsupplier.supplier_name}}</option>
</select> <br> <span style="color: red"
ng-show="addstock.supplier.$touched && addstock.supplier.$invalid">Supplier
is Required.</span>
</div>
<div class="form-group col-md-3">
<input type="text" class="form-control"
ng-model="productStock.invoice" id="invoice" name="invoice"
placeholder="Enter Invoice Number" required> <br> <span
style="color: red"
ng-show="addstock.invoice.$touched && addstock.invoice.$invalid">Enter
Invoice Number.</span>
</div>
<div class="form-group col-md-3">
<input type="date" name="productdate" id="productdate"
ng-model="productStock.productdate" class="form-control"
required=""> <br> <span style="color: red"
ng-show="addstock.productdate.$touched && addstock.productdate.$invalid">Date
is Required.</span>
</div>
</div>
<h3 class="m-t-0 m-b-30 header-title text-center">ITEMS</h3>
<div ng-repeat="productStock in productStocks"
style="margin-bottom: 10px;">
<div class="form-group">
<!--<input type="text" name="product_name" ng-model="productsStock.product_name" required="" placeholder="Product Name" class="form-control" id="product_name">-->
<select name="productStock_name"
ng-model="productStock.productStock" class="form-control"
required="">
<option value="">Select a Product</option>
<option ng-repeat="products in allproducts"
value="{{products.product_id}}">
{{products.product_name}}</option>
</select> <br> <span style="color: red"
ng-show="addstock.productStock_name.$touched && addstock.productStock_name.$invalid">Product
Name Required.</span>
</div>
<div class="form-group">
<input id="productstock_qty" type="number" min="1" required=""
name="productstock_qty" ng-model="productStock.productstock_qty"
placeholder="Product Quantity" class="form-control"> <br>
<span style="color: red"
ng-show="addstock.productstock_qty.$touched && addstock.productstock_qty.$invalid">Product
Quantity required.</span>
</div>
<div class="form-group">
<input id="productstock_price" type="number" min="1"
ng-model="productStock.productstock_price"
name="productstock_price" placeholder="Product Price"
class="form-control" maxlength="15" size="10" required="">
<br> <span style="color: red"
ng-show="addstock.productstock_price.$touched && addstock.productstock_price.$invalid">Price
required.</span>
</div>
<div class="form-group">
<select name="product_units"
ng-model="productStock.productstock_units" class="form-control"
required="">
<option value="">Select Units</option>
<option ng-repeat="units in allunits" value="{{units.unit_id}}">
{{units.unit_name}}</option>
</select> <br> <span style="color: red"
ng-show="addstock.product_units.$touched && addstock.product_units.$invalid">Units
is required.</span>
</div>
<div class="form-group">
<input id="productstock_cgst" type="text"
ng-model="productStock.productstock_cgst" name="productstock_cgst"
placeholder="CGST" class="form-control" maxlength="10" size="6"
required=""> <br> <span style="color: red"
ng-show="addstock.productstock_cgst.$touched && addstock.productstock_cgst.$invalid">required.</span>
</div>
<div class="form-group">
<input id="productstock_sgst" type="text"
ng-model="productStock.productstock_sgst" name="productstock_sgst"
placeholder="SGST" class="form-control" maxlength="10" size="6"
required=""> <br> <span style="color: red"
ng-show="addstock.productstock_sgst.$touched && addstock.productstock_sgst.$invalid">required.</span>
</div>
<!--<div class="form-group">-->
<!-- <input id="productstock_gst" type="text" ng-model="productStock.productstock_gst" ng-keydown="keydownevt()" name="productstock_gst" placeholder="GST" class="form-control" maxlength="10" size="6" required="">-->
<!-- <br>-->
<!-- <span style="color:red" ng-show="addstock.productstock_gst.$touched && addstock.productstock_gst.$invalid">required.</span> -->
<!--</div>-->
<div class="form-group">
<input id="productstock_total" type="text"
ng-model="productStock.productstock_total"
name="productstock_total" placeholder="Total" class="form-control"
required=""> <br> <span style="color: red"
ng-show="addstock.productstock_total.$touched && addstock.productstock_total.$invalid">Total
is required</span>
</div>
<button class="btn btn-danger btn-sm" ng-show="$last"
ng-click="removeStock()">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
<!-- ng-repeat close for add dynamic product field-->
<div class="form-group text-right m-b-0">
<button class="addfields btn btn-info waves-effect waves-light"
ng-click="addstockproduct()">Add Stock</button>
</div>
<div class="form-group text-right m-b-0 pull-right"
style="margin-top: 10px;">
<button type="submit" ng-click="" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-warning">Reset</button>
</div>
</form>
</div>
angularjs Controller:-
//Add Dynamic Fields.
$scope.productStocks = [{id: 'firstField2'}];
$scope.addstockproduct = function(){
var newItemNo2 = $scope.productStocks.length+1;
$scope.productStocks.push({'id':'field'+newItemNo2});
}
$scope.removeStock = function() {
var itemLast2 = $scope.productStocks.length-1;
$scope.productStocks.splice(itemLast2);
};
angularjs code for add records:-
$scope.productStock={};
$scope.suplier_succ = false;
$scope.suplier_err = false;
$scope.saveStockPurchaseInvoice=function(){
$http({
method: 'post',
url: 'stock/insert_stock',
data: $scope.productStock,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data)
{
if (data == 1) {
$scope.suplier_succ = $scope.suplier_succ ? false : true;
$scope.succ = "Stock added successfully";
$timeout(function () {
$(".modal").modal("hide");
}, 3000);
// $scope.formsup = {}; // clears input fields
// $scope.addsuppler.$setPristine();
// $scope.addsuppler.$setUntouched();
} else{
$scope.suplier_err = $scope.suplier_err ? false : true;
$scope.err = "Stock insertion failed! Try again.";
}
});
};
Codeigniter Controller:-
public function insert_stock(){
$request = json_decode(file_get_contents('php://input'), TRUE);
print_r($request);
}
enter image description here
My Result:-(All Records value is not POST)
enter image description here
I had the same problem with form data post.
I was able to resole it by setting headers: { 'Content-Type': undefined } and transformRequest: angular.identity in http request.
below is my sample code.
function Upload(containerName, objFile, objParams) {
var deferred = $q.defer();
var frmData = new FormData();
frmData.append('file', objFile);
var req = {
method: 'POST',
url: window.APIBaseUrl + 'containers/' + containerName + '/upload',
data: frmData,
params: objParams,
headers: { 'Content-Type': undefined },
transformRequest: angular.identity,
dataType: "json"
}
$http(req).then(function (response) {
deferred.resolve(response.data);
}, function (err) {
deferred.reject(handleHttpError(err));
$log.error("Error in upload", err);
});
return deferred.promise;
}
This May help you
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-sm-6" style="width:50%;">
<div class="card-box">
<form class="form-inline" name="addstock"
ng-submit="saveStockPurchaseInvoice()">
<h3 class="m-t-0 m-b-30 header-title text-center">Invoice
Details</h3>
<div class="row" style="margin-bottom: 20px;">
<div class="form-group col-md-3" style="">
<select name="supplier" ng-model="productStock.suppliername"
class="form-control" required="">
<option value="">Select a Supplier</option>
<option ng-repeat="allsupplier in supplier"
value="{{allsupplier.supplier_id}}">
{{allsupplier.supplier_name}}</option>
</select> <br> <span style="color: red"
ng-show="addstock.supplier.$touched && addstock.supplier.$invalid">Supplier
is Required.</span>
</div>
<div class="form-group col-md-3">
<input type="text" class="form-control"
ng-model="productStock.invoice" id="invoice" name="invoice"
placeholder="Enter Invoice Number" required> <br> <span
style="color: red"
ng-show="addstock.invoice.$touched && addstock.invoice.$invalid">Enter
Invoice Number.</span>
</div>
<div class="form-group col-md-3">
<input type="date" name="productdate" id="productdate"
ng-model="productStock.productdate" class="form-control"
required=""> <br> <span style="color: red"
ng-show="addstock.productdate.$touched && addstock.productdate.$invalid">Date
is Required.</span>
</div>
</div>
<h3 class="m-t-0 m-b-30 header-title text-center">ITEMS</h3>
<div ng-repeat="item in productStocks track by $index"
style="margin-bottom: 10px;">
<div class="form-group">
<!--<input type="text" name="product_name" ng-model="productsStock.product_name" required="" placeholder="Product Name" class="form-control" id="product_name">-->
<select name="productStock_name"
ng-model="productStock.items[$index].productStock" class="form-control"
required="">
<option value="">Select a Product</option>
<option ng-repeat="products in allproducts"
value="{{products.product_id}}">
{{products.product_name}}</option>
</select> <br> <span style="color: red"
ng-show="addstock.productStock_name.$touched && addstock.productStock_name.$invalid">Product
Name Required.</span>
</div>
<div class="form-group">
<input id="productstock_qty" type="number" min="1" required=""
name="productstock_qty" ng-model="productStock.items[$index].productstock_qty"
placeholder="Product Quantity" class="form-control"> <br>
<span style="color: red"
ng-show="addstock.productstock_qty.$touched && addstock.productstock_qty.$invalid">Product
Quantity required.</span>
</div>
<div class="form-group">
<input id="productstock_price" type="number" min="1"
ng-model="productStock.items[$index].productstock_price"
name="productstock_price" placeholder="Product Price"
class="form-control" maxlength="15" size="10" required="">
<br> <span style="color: red"
ng-show="addstock.productstock_price.$touched && addstock.productstock_price.$invalid">Price
required.</span>
</div>
<div class="form-group">
<select name="product_units"
ng-model="productStock.items[$index].productstock_units" class="form-control"
required="">
<option value="">Select Units</option>
<option ng-repeat="units in allunits" value="{{units.unit_id}}">
{{units.unit_name}}</option>
</select> <br> <span style="color: red"
ng-show="addstock.product_units.$touched && addstock.product_units.$invalid">Units
is required.</span>
</div>
<div class="form-group">
<input id="productstock_cgst" type="text"
ng-model="productStock.items[$index].productstock_cgst" name="productstock_cgst"
placeholder="CGST" class="form-control" maxlength="10" size="6"
required=""> <br> <span style="color: red"
ng-show="addstock.productstock_cgst.$touched && addstock.productstock_cgst.$invalid">required.</span>
</div>
<div class="form-group">
<input id="productstock_sgst" type="text"
ng-model="productStock.items[$index].productstock_sgst" name="productstock_sgst"
placeholder="SGST" class="form-control" maxlength="10" size="6"
required=""> <br> <span style="color: red"
ng-show="addstock.productstock_sgst.$touched && addstock.productstock_sgst.$invalid">required.</span>
</div>
<!--<div class="form-group">-->
<!-- <input id="productstock_gst" type="text" ng-model="productStock.productstock_gst" ng-keydown="keydownevt()" name="productstock_gst" placeholder="GST" class="form-control" maxlength="10" size="6" required="">-->
<!-- <br>-->
<!-- <span style="color:red" ng-show="addstock.productstock_gst.$touched && addstock.productstock_gst.$invalid">required.</span> -->
<!--</div>-->
<div class="form-group">
<input id="productstock_total" type="text"
ng-model="productStock.items[$index].productstock_total"
name="productstock_total" placeholder="Total" class="form-control"
required=""> <br> <span style="color: red"
ng-show="addstock.productstock_total.$touched && addstock.productstock_total.$invalid">Total
is required</span>
</div>
<button class="btn btn-danger btn-sm" ng-show="$last"
ng-click="removeStock()">
<span class="glyphicon glyphicon-remove"></span>
</button>
</div>
<!-- ng-repeat close for add dynamic product field-->
<div class="form-group text-right m-b-0">
<button class="addfields btn btn-info waves-effect waves-light"
ng-click="addstockproduct()">Add Stock</button>
</div>
<div class="form-group text-right m-b-0 pull-right"
style="margin-top: 10px;">
<button type="submit" ng-click="" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-warning">Reset</button>
</div>
</form>
</div>
</div>
<div style="width:50%">
<pre>{{productStock | json}}</pre>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http) {
$scope.productStocks = [{id: 'firstField2'}];
$scope.supplier = [{supplier_id:1, supplier_name:'abc'}];
$scope.allproducts = [{ product_name:'qwerty',product_id:1 }];
$scope.allunits = [{ unit_id:1,unit_name:'iop'}];
$scope.addstockproduct = function(){
var newItemNo2 = $scope.productStocks.length+1;
$scope.productStocks.push({'id':'field'+newItemNo2});
}
$scope.removeStock = function() {
var itemLast2 = $scope.productStocks.length-1;
$scope.productStocks.splice(itemLast2);
};
$scope.productStock={};
$scope.suplier_succ = false;
$scope.suplier_err = false;
$scope.saveStockPurchaseInvoice=function(){
$http({
method: 'POST',
url: 'http://abcd/insert', //change to your url
data: JSON.stringify($scope.productStock),
//headers: {'Content-Type': 'application/x-www-form-urlencoded'}
headers: { 'Content-Type': undefined },
transformRequest: angular.identity,
dataType: "json"
// 'Content-Type':'application/json'
}).then(function (response)
{
if (data == 1) {
$scope.suplier_succ = $scope.suplier_succ ? false : true;
$scope.succ = "Stock added successfully";
$timeout(function () {
$(".modal").modal("hide");
}, 3000);
// $scope.formsup = {}; // clears input fields
// $scope.addsuppler.$setPristine();
// $scope.addsuppler.$setUntouched();
} else{
$scope.suplier_err = $scope.suplier_err ? false : true;
$scope.err = "Stock insertion failed! Try again.";
}
});
};
//$request = json_decode(file_get_contents('php://input'), TRUE);
// print_r($request);
});
</script>
</body>
</html>

How to clear directive ngmodel value from controller?

I am newbie in angularjs. I have create directive called newActivity and bind object, variables and function with this directive. Here i want that when i clicked on submit/cancel button then it should clear all ng-model bind variables from both newActivity directive and from controller.
Example
Directive:-
angular
.module('app')
.directive('newActivity', newActivity);
function newActivity() {
var directive = {
restrict: 'E',
scope: {
newActivity: '=',
underUsers: '=',
actTypes: '=',
callTypes: '=',
forAct: '#',
action: '&',
cancel: '&'
},
template: '<div class="box-header"> <h2>{{forAct}} {{newActivity.type | uppercase}} Activity</h2> </div> <div class="box-divider m-a-0">' +
'</div> <div class="box-body"> <form ng-submit="action()" name="newActForm" role="form">' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-model="newActivity.type" ng-options="actType.type as actType.title for actType in actTypes"></select></div></div> ' +
'<div ng-if="newActivity.type==\'notes\'" class="form-group row"><div class="col-sm-10"><textarea required ng-model="newActivity.description" class="form-control" rows="2"></textarea></div></div> ' +
'<div ng-if="newActivity.type==\'meeting\' || newActivity.type==\'email\' || newActivity.type==\'task\'" class="form-group row"><div class="col-sm-10">' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Date" type="text" class="form-control w-auto inline" ng-model="newActivity.date" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-left="fa fa-chevron-left" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Time" type="text" class="form-control" ng-model="newActivity.time" data-time-format="HH:mm" data-time-type="number" name="time2" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Reminder</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isReminder" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isReminder" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Date" type="text" class="form-control w-auto inline" ng-model="newActivity.reminder.date" data-icon-left="fa fa-chevron-left" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div> ' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Time" type="text" class="form-control" ng-model="newActivity.reminder.time" data-time-format="HH:mm" data-time-type="number" name="time1" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div> ' +
'</div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Assign To Other</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isAssignOther" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isAssignOther" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-model="newActivity.assignTo" ng-options="user._id as user.name for user in underUsers"></select></div></div> ' +
'</div>' +
'<div class="form-group row"><div class="col-sm-10"><textarea required placeholder="Remarks" class="form-control" ng-model="newActivity.description" rows="2"></textarea></div></div>' +
'</div></div> ' +
'<div ng-if="newActivity.type==\'call\'" class="form-group row"><div class="col-sm-10">' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-init="newActivity.callType = \'out\'" ng-model="newActivity.callType" ng-options="callType.type as callType.title for callType in callTypes"></select></div></div>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Date" type="text" class="form-control w-auto inline" ng-model="newActivity.date" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-left="fa fa-chevron-left" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Select Time" type="text" class="form-control" ng-model="newActivity.time" data-time-format="HH:mm" data-time-type="number" name="time2" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Reminder</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isReminder" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isReminder" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Date" type="text" class="form-control w-auto inline" ng-model="newActivity.reminder.date" data-icon-left="fa fa-chevron-left" data-date-format="dd-MM-yyyy" data-autoclose="true" data-date-type="number" data-icon-right="fa fa-chevron-right" placeholder="From" bs-datepicker></div></div> ' +
'<div class="form-group row"><div class="col-sm-10"><input required placeholder="Reminder Time" type="text" class="form-control" ng-model="newActivity.reminder.time" data-time-format="HH:mm" data-time-type="number" name="time1" data-icon-up="fa fa-chevron-up" data-icon-down="fa fa-chevron-down" bs-timepicker></div></div> ' +
'</div>' +
'<div class="form-group row"> <label class="col-sm-4 form-control-label">Assign To Other</label> <div class="col-sm-8"> <div class="checkbox"> <label class="ui-switch m-t-xs m-r"> <input type="checkbox" ng-model="newActivity.isAssignOther" value=""> <i></i> </label> </div> </div> </div>' +
'<div ng-if="newActivity.isAssignOther" col-sm-8>' +
'<div class="form-group row"><div class="col-sm-10"><select class="form-control" ng-model="newActivity.assignTo" ng-options="user._id as user.name for user in underUsers"></select></div></div> ' +
'</div>' +
'<div class="form-group row"><div class="col-sm-10"><textarea required placeholder="Remarks" class="form-control" ng-model="newActivity.description" rows="2"></textarea></div></div>' +
'</div></div> ' +
'<div class="form-group row m-t-md"> <div class="col-sm-offset-2 col-sm-10">' +
'<input type="submit" class="btn success" value="Save">' +
'<button type="button" style="margin-left:5px" ng-click="cancel()" class="btn danger">Cancel</button>' +
'</div></form> </div>',
link: function(scope, element, attrs) {},
controller: function($scope) {}
};
return directive;
}
Controller:-
function addNewActivity() {
vm.loading = true;
vm.newActivity = {}; //Here vm.newActivity is not clear fields from "newActivity" directive
}
HTML:-
<new-activity for-act='Add' action='addNewActivity()' cancel='closeAddNewActivity()' new-activity='newActivity' under-users='underUsers' act-types='actTypes' call-types='callTypes'></new-activity>
You are using the controllerAs synthax, you should prefix your calls to functions and use of variables with the name you specify (here vm).
For example if your code:
<new-activity for-act='Add'
action='addNewActivity()'
cancel='closeAddNewActivity()'
new-activity='newActivity'
under-users='underUsers'
act-types='actTypes'
call-types='callTypes'>
</new-activity>
Shoud be:
<new-activity for-act='Add'
action='vm.addNewActivity()'
cancel='vm.closeAddNewActivity()'
new-activity='vm.newActivity'
under-users='vm.underUsers'
act-types='vm.actTypes'
call-types='vm.callTypes'>
</new-activity>
Use new-activity='vm.newActivity' instead of new-activity='newActivity
And also use vm.addNewActivity() and vm.closeAddNewActivity()
So that every bindings have the correct source from your controller
<new-activity for-act='Add' action='vm.addNewActivity()' cancel='vm.closeAddNewActivity()' new-activity='vm.newActivity' under-users='vm.underUsers' act-types='vm.actTypes' call-types='vm.callTypes'></new-activity>

How to validate forms in Angular JS

i'm a newbie in angular JS. and i was trying the input type="text", i'm retrieving my name from my controller and i was using $dirty and $invalid to validate my data but it isn't showing when i make the input field empty.
JS Fiddle : https://jsfiddle.net/U3pVM/24718/
var FormValidations = angular.module('FormValidations',[]);
FormValidations.controller('FormsValidations', function( $scope ){
$scope.formsToBeValidated = {
firstName : 'Daniel'
};
});
Unless you add name attribute to form level field, that will not get included in form object when you specified in the name attribute on form, currentlyh it is name="studentForm". Do add name="firstName" to your input field
<input type="text" class="form-control"
name="firstName" ng-model="formsToBeValidated.firstName" required/>
Forked Fiddle
For more information you could refer this answer, which has more detailed
More convenient way to solve this issue would be using ng-messages instead of using ng-show/ng-hide, for that you have to include ng-messages module with its ng-messages dependency.
you should try this:
<input name="firstName" type="text" class="form-control"
ng-model="formsToBeValidated.firstName" required>
fiddle
as other says , add "name" attribute to your input.
I made a custom directive to display error on input using ng-message ( so you have to include it )
directives.directive('inputerrormsg', function () {
return {
replace: true,
restrict: 'E',
plain: true,
scope: {
inputdata: "=",
dpattern: '#'
},
template: '<div class="help-block has-error text-center" ng-messages="inputdata[\'$error\']" >' +
'<p ng-message="required">{{\'The field is required\'| translate }}</p>' +
'<p ng-message="minlength">{{\'Input too short\'| translate }}</p>' +
'<p ng-message="maxlength">{{\'Input too long\'| translate }}</p>' +
'<p ng-message="email">{{\'Email invalid\'| translate }}</p>' +
'<p ng-message="date">{{\'Date invalid\'| translate }}</p>' +
'<p ng-message="number">{{\'Write number only\'| translate }}</p>' +
'<p ng-message="pattern">' +
'<span ng-switch="dpattern">' +
'<span ng-switch-when="date">{{\'Date incorrecte: YYYY, YYYY/MM, YYYY/MM/DD\' |translate}}</span>' +
'<span ng-switch-default>{{\'Saisir uniquement des lettres\'| translate }}</span>' +
'</span>' +
'</p>' +
'</div>'
}
});
USAGE :
required field
<div style="padding-left: 0px;" ng-class="{ 'has-error' : !formDeter.scientificname.$valid">
<div class="input-group no-padding">
<input type="text"
class="form-control input-md" name="scientificname"
required />
<span class="input-group-addon">
<span class="glyphicon glyphicon-question-sign"></span>
</span>
</div>
<dir.inputerrormsg inputdata="formDeter.scientificname" ></dir.inputerrormsg>
EMail :
<div class="form-group row" ng-class="{ 'has-error' : !formData.email.$valid }">
<label class="col-xs-4 control-label">{{"Email" | translate }}</label>
<div class="col-xs-8 input-group">
<input type="email" class="form-control input-md" ng-model="email" name="email" id="email" required
placeholder="{{'Email' | translate }}"/>
</div>
<dir.inputerrormsg inputdata="formData.email" dpattern="email" ></dir.inputerrormsg>
</div>
Number only :
<div class="form-group row" ng-class="{ 'has-error' : !formLocalisation.decimallongitude.$valid }">
<label class="col-xs-4 control-label">{{"Longitude" | translate }}</label>
<div class="col-xs-8 input-group">
<input type="number" popover-trigger="focus" placeholder="{{'Longitude' | translate }}"
class="form-control input-md"
ng-model="specimen.decimallongitude" name="decimallongitude"
/>
<span class="input-group-addon" >
<span class="glyphicon glyphicon-question-sign"></span>
</span>
</div>
<dir.inputerrormsg inputdata="formLocalisation.decimallongitude" ></dir.inputerrormsg>
</div>
...
You didn't specified name to your input. Try this:
<form name="studentForm" novalidate>
<input type="text" class="form-control" name ="input" ng-model="formsToBeValidated.firstName" required>
<span studentForm.input.$error.required && studentForm.input.$dirty>First Name is Required</span>
</form>

AngularJs text filed value undefined

I have one start date field (date picker) and a client status (drop down) fields.
If I select a date in the date picker, when passing date value to server it is showing undefined, but if I type any value with date in that field, that exact value is correctly sent to the server.
Inside the drop down list I am not getting the value it is coming undefined.
My code is:
<div class="form-group">
<label for="inputPassword3" class="col-sm-3 control-label">Client Name</label>
<div class="col-sm-9">
<div ng-controller="MyCntrl" >
<select class="form-control" name="clientname" id="clientname" class="form-control" ng-model="vm.clientname" ng-change="change(myColor)" >
<option value="">Select Client Name</option>
<option ng-repeat="color in colors"
value="{{color.value}}"
ng-selected="{{color.value == myColor}}" name="clientname" id="clientname" class="form-control" ng-model="vm.clientname">
{{color.clientname}}
</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-3 control-label">Project Startdate</label>
<div class="col-sm-9">
<!-- <input type="text" name="prjstartdate" id="prjstartdate" class="form-control" ng-model="vm.user.prjstartdate" required />-->
<div class="container" id="sandbox-container">
<div class="input-daterange input-group" id="datepicker" name="prjstartdate" id="prjstartdate" class="form-control" ng-model="vm.prjstartdate">
<input type="text" name="prjstartdate" id="prjstartdate" class="form-control" ng-model="vm.prjstartdate" required />
</div>
</div>
<div class="modal-footer" ng-controller="MyCntrlsave">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" ng-click="savedetails()">Save changes</button>
</div>
</div>
</div>
js code:
<script type="text/javascript">
function MyCntrlsave($scope,$http) {
$scope.savedetails = function() {
var vm = this;
var projectname=$scope.vm.prjname;
var cilentname=$scope.vm.color;
var clientstatus=$scope.vm.prjsta;
var prjstartdate=$scope.vm.prjstartdate;
var prjenddate=$scope.vm.prjenddate;
var prjurl=$scope.vm.prjurl;
alert("projectname::"+projectname)
alert("prjstartdate::"+prjstartdate)
}
}

Angular form validation is not working

I have the following form :
UPDATE
<script type="text/ng-template" id="form-profile.html">
<form id="f1" name="form">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="formData.name" ng-class="submitted ? 'ng-dirty' : ' ' " required autofocus>
<span style="color:red" ng-show="form.name.$dirty || form.name.$invalid">Name is required</span>
</div>
<div class="form-group">
<label for="name">E-mail</label>
<input type="text" class="form-control" name="email" ng-model="formData.email" ng-class="submitted ? 'ng-dirty' : ' '" required autofocus>
<span style="color:red" ng-show="f1.email.$dirty && f1.email.$invalid">
<span ng-show="f1.email.$error.required">Email is required.</span>
</span>
</div>
<div class="form-group">
<label for="Cellphone">Mobil nr.</label>
<input type="text" class="form-control" name="Cellphone" ng-model="formData.Cellphone" ng-class="submitted ? 'ng-dirty' : ' '" required autofocus>
<span style="color:red" ng-show="f1.Cellphone.$dirty && f1.Cellphone.$invalid">
<span ng-show="f1.Cellphone.$error.required">Cellphone is required.</span>
</span>
</div>
<div class="form-group">
<label for="address">Adresse</label>
<input type="text" class="form-control" name="address" ng-model="formData.address">
</div>
<div class="form-group col col-33 col-offset-67">
<a ui-sref="front.form.organisation" class="button icon-right ion-chevron-right button-energized .col-offset-50">
Next
</a>
</div>
</form>
</script>
When I press next I want the form to disable the next button and show me the errors.
I have tried with name so far and I did not get the errors.
Thank you
Please see demo below
ng-show="f1.name.$dirty <-- f1 that's form name not id
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope) {
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<form name="f1">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="formData.name" required autofocus>
<span style="color:red" ng-show="f1.name.$dirty && f1.name.$invalid">Name is required</span>
</div>
</form>
</div>

Resources