Dynamic ng-model with ng-repeat - javascript

I would like to create dynamically some input fields, that I used ng-repeat with ng-model. I meet some problems. ng-model without ng-repeat works correctly (transitPointStart). transits should work exactly the same, but they don't. What am I missing?
(link to plunker on the bottom)
transitPointStart:
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="field_start">Start Point</label>
<input type="text" class="form-control" name="field_start" id="field_start"
ng-model="transitPointStart.city" placeholder="e.g. London"
/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="field_start_date">Date</label>
<div class="input-group">
<input id="field_start_date" type="text" class="form-control" placeholder="YYYY-MM-DD HH:MM"
name="field_start_date"
datetime-picker="{{dateformat}}" ng-model="transitPointStart.date"
is-open="datePickerOpenStatus.field_start_date"
/>
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="openCalendar('field_start_date')"><i
class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</div>
</div>
transits:
<div class="row" ng-repeat="transit in transits">
<!--TEST-->
<!--<div> Model: {{transit.modelName}} </div>-->
<!--<div> dateModel: {{transit.dateModelName}} </div>-->
<!--<div> datePicker: {{transit.datePickerName}} </div>-->
<!--<div> fieldName: {{transit.fieldName}} </div>-->
<!--<div> fieldDateName: {{transit.fieldDateName}} </div>-->
<!--<div> button: {{transit.buttonDateName}} </div>-->
<!--/TEST-->
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="transit.fieldName">Transit {{$index+1}}</label>
<input type="text" class="form-control" name="transit.fieldName" id="transit.fieldName"
ng-model="transit.modelName" placeholder="transit"
/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="transit.fieldDateName">Date {{$index+1}}</label>
<div class="input-group">
<input id="transit.fieldDateName" type="text" class="form-control" placeholder="e.g"
name="transit.fieldDateName"
datetime-picker="{{dateformat}}" ng-model="transit.dateModelName"
is-open="transit.datePickerName"
/>
<span class="input-group-btn">
<button type="button" class="btn btn-default"
ng-click="transit.buttonDateName"><i
class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-2">
<span class="btn btn-primary" ng-click="addTransit()" ng-if="transits.length < 3">Add transit</span>
</div>
<div class="col-lg-2"></div>
</div>
controller:
$scope.transits = [];
$scope.addTransit = function () {
var tempId = $scope.transits.length + 1;
var tempName = "transitPoint_" + tempId;
var tempModelName = tempName + ".city"; // Here I would like to have access to transitPoint.city
var tempDateName = tempName + ".date"; // as above (transitPoint.date)
var tempDate = "datePickerOpenStatus.field_transit_date_" + tempId;
var tempFieldName = "field_transit_" + tempId;
var tempFieldDateName = "field_transit_date_" + tempId;
var tempButton = "openCalendar('" + tempFieldDateName + "')";
$scope.transits.push({
modelName: tempModelName,
dateModelName: tempDateName,
datePickerName: tempDate,
fieldName: tempFieldName,
fieldDateName: tempFieldDateName,
buttonDateName: tempButton
});
}
/*
{...} - rest of code, sending queries (vm.save() ect.)
*/
$scope.datePickerOpenStatus = {};
$scope.datePickerOpenStatus.field_start_date = false;
$scope.datePickerOpenStatus.field_end_date = false;
// I should've used loop here
$scope.datePickerOpenStatus.field_transit_date_1 = false;
$scope.datePickerOpenStatus.field_transit_date_2 = false;
$scope.datePickerOpenStatus.field_transit_date_3 = false;
$scope.openCalendar = function (date) {
$scope.datePickerOpenStatus[date] = true;
};
Demo: Plunker

Some of the bindings in your HTML are not correct. You need to use interpolation (the {{ }} format) whenever you need to emit data from the model into the HTML.
For example, when assigning IDs, you have:
<input id="transit.fieldDateName" type="text" class="form-control" placeholder="e.g" name="transit.fieldDateName" ...
This should be:
<input id="{{transit.fieldDateName}}" type="text" class="form-control" placeholder="e.g" name="{{transit.fieldDateName}}" ...
Second, your ng-click syntax is not correct. You should not create the openCalendar expression in JavaScript, but in your HTML, like so:
<button type="button" class="btn btn-default" ng-click="openCalendar(transit.fieldDateName)">
I think your Plnkr is missing some scripts and/or steps to make the calendar work, but these changes will at least cause your openCalendar function to get called.

Related

jQuery Cloning and incrementing input, textarea, that has name, id and for

I'm still very new to jQuery, and would need help to how to increment 3 elements in this code.
name, id & for.
The name consist of products[0]category, id consist of checkbox[0], for consist of checkbox[0] which is for labels on the checkbox that id use.
I've tried searching for examples. But all them haven't found any good results that i could learn from unfortunately. So in the codes below, they're not there to increase increment as i have totally no idea what else i can do to increase increment numbering.
$(document).ready(function() {
let $append = $('#append');
// append location's data listing
$append.on('change', '.location', function(){
var value = $(this).val();
$('.location_id').val($('#locations [value="'+value+'"]').data('locationid'));
$('.loc_desc').val($('#locations [value="'+value+'"]').data('locdesc'));
});
// enable checkbox for serialnumbers
$append.on('change','.enable-serial', function(){
let $item = $(this).closest('.product-item');
let $checkbox = $item.find('.enable');
$checkbox.prop('disabled', !this.checked);
});
// ctrl for key in checkbox
$append.on('click', '.keyin-ctrl', function() {
let $container = $(this).closest('.product-item');
let $serial = $container.find('.serial');
$container.find('.display').val(function(i, v) {
return v + $serial.val() + ';\n';
});
$serial.val('').focus();
});
// ctrl for del textarea
$append.on('click', '.undo-ctrl', function() {
let $container = $(this).closest('.product-item');
$container.find('.display').val('');
});
// clone product, increment products[x]var
$('#add_product').on('click', function() {
var itemNo = $('.product-item').length + 1;
var index = $('.product-item').length;
var regex = /^(.+?)(\d+)$/i;
let $product = $append.find('.product-item.template')
.clone()
.show()
.removeClass('template')
.insertAfter('.product-item:last');;
$product.find('span').text('#' + itemNo);
$product.find(':checkbox').prop('checked', false);
$product.find('.enable').prop('disabled', true);
$product.find('input, textarea').val('');
$('#append').append($product);
});
// delete product, but remain original template intact
$('#delete_product').on('click', function(){
var itemNo = $('.product-item').length + 1;
let $product = $append.find('.product-item:last:not(".template")');
$product.remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="shadow border">
<h4>{{ __('Product Details') }}</h4>
<hr>
<form method="post" action="">
<!-- Multiple Product addition -->
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Product Setting') }}</label><br/>
<div class="col-sm-5">
<button type="button" id="add_product" class="btn btn-dark">{{ __('Add Product') }} <i class="fas fa-plus-square"></i></button>
<button type="button" id="delete_product" class="btn btn-dark ml-3">{{ __('Delete Last Product') }} <i class="fas fa-minus-square"></i></button>
</div>
</div>
<hr>
<!-- Frist Group -->
<div class="product" id="append">
<!-- Product Details -->
<div class="product-item template">
<span>#1</span>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Category') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]category" type="text" placeholder="eg. 333" maxlength="3"required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Code') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]code" type="text" placeholder="eg. 22" maxlength="2" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Partnumber') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]partnumber" type="text" placeholder="eg. NGH92838" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Brand') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]brand" type="text" placeholder="eg. Rototype" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Quantities') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]qty" type="number" placeholder="eg. 1" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __("Location") }}</label>
<div class="col-sm-2">
<input class="form-control location" type="text" name="products[0]loc_name" list="locations" value="">
<input type="hidden" class="location_id" name="products[0]location_id" value="">
<input type="hidden" class="loc_desc" name="products[0]loc_desc" value="">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __("Description") }}</label>
<div class="col-sm-8">
<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Seial Number(s)') }}</label>
<div class="col-sm-5">
<input class="form-control enable serial" maxlength="25" placeholder="Key in Serial Number and hit button 'Key In'" disabled>
</div>
<div class="col-sm-5">
<button class="btn btn-dark enable keyin-ctrl" type="button" disabled>{{ __('Key In') }}</button>
<button class="btn btn-dark enable undo-ctrl" type="button" disabled>{{ __('Del') }}</button>
<input class="form-check-input ml-4 mt-2 pointer enable-serial" id="checkbox[0]" type="checkbox">
<label class="form-check-label ml-5 pointer" for="checkbox[0]">{{ __('tick to enable serialnumber')}}</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-5">
<textarea class="form-control display" name="products[0]serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>
</div>
</div>
<hr>
</div>
<!-- append start -->
</div>
<div class="form-group row">
<div class="col-sm-12 ">
#csrf
<button type="submit" class="btn btn-dark float-right ml-4">Next <i class="fas fa-caret-right"></i></button>
<!--<button type="button" class="btn btn-secondary float-right" onclick="history.back()">Previous</button>-->
</div>
</div>
<datalist id="locations">
#foreach($locations as $location)
<option value="{{ $location->loc_name}}" data-locationid="{{ $location->location_id }}" data-locdesc="{{ $location->loc_desc }}"></option>
#endforeach
</datalist>
</form>
</div>
</main>
So how do I actually achieve this to add increment to the NAME, ID and FOR my clones?
From the original template of products[0]variable to products[1]variable, checkbox[0] to checkbox[1]
If you want to increment either an ID, class, etc. you can't use .clone(), like the documentation warns:
Using .clone() has the side-effect of producing elements with
duplicate id attributes, which are supposed to be unique. Where
possible, it is recommended to avoid cloning elements with this
attribute or using class attributes as identifiers instead.
You'll have to do it "manually", following a very simple example below:
$( "#addrow" ).click(function() {
var count = $("#product").children().length;
$("#product").append("<input id='field[" + count + "]' type='text'>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="product">
</div>
<input id="addrow" type="button" value="Add field">

jQuery only run function for element that gets clicked

I got a small problem that i have no clue how to solve. This HTML/PHP code bellow gets different values from a database and outputs them into the different input fields.
The HTML/PHP bellow is one element, and multiple of them are made with different values from the database. Then i got a small javascript that calulates some different values from the values that are inputted. The problem is that i got lets say 5 elements, and only wants to calculate for one of them, but if i press the "btn-oppdater" button it calculates for all the different elements.
How do i make it only calculate for the element where the button is?
Script
$('.btn-oppdater').click(function(){
$(".kval_spill").each(function(){
var fieldShow = $(this).next('.kval_spill_inner');
var b_value_kval_1 = fieldShow.find('.b_value_kval_1')[0].value;
var b_odds_kval_1 = fieldShow.find('.b_odds_kval_1')[0].value;
var e_odds_kval_1 = fieldShow.find('.e_odds_kval_1')[0].value;
var gebyr_kval = '0.02'
var q_value = ((b_odds_kval_1 / (e_odds_kval_1 - gebyr_kval)) * b_value_kval_1);
var q_tap = (b_odds_kval_1 - 1) * b_value_kval_1 - (e_odds_kval_1 - 1) * q_value;
var q_value_fixed = q_value.toFixed(2);
var q_tap_fixed = q_tap.toFixed(2);
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
});
});
HTML/PHP
<?php while ($row = mysqli_fetch_assoc($result2)) { echo '
<form style="margin-top: 10px;" action="" method="post" class="">
<input type="hidden" class="kval_spill">
<div class="kval_spill_inner">
<input class="" type="hidden" name="id" value="'.$row['id'].'">
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_kamp_1" name="kval_kamp_1" value ="'.$row['kval_kamp_1'].'" placeholder="Kamp">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control b_value_kval_1" name="b_value_kval_1" value ="'.$row['b_value_kval_1'].'" placeholder="Spill verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control b_odds_kval_1" name="b_odds_kval_1" value ="'.$row['b_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_marked_1" name="kval_marked_1" value ="'.$row['kval_marked_1'].'" placeholder="Type marked">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control text-info q_value_1" name="q_value_1" value ="'.$row['q_value_1'].'" placeholder="Lay verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control e_odds_kval_1" name="e_odds_kval_1" value ="'.$row['e_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text">Tap</span>
</div>
<input type="text" class="form-control text-danger q_tap_1" name="q_tap_1" value ="'.$row['q_tap_1'].'" placeholder
="0.00" readonly>
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="col-auto">
<button type="button" class="btn btn-outline-secondary btn-oppdater">Regn ut</button>
</div>
</div>
</div>
</form>
<br>
'; }?>
Replace $(".kval_spill") with $(this).closest("form").find(".kval_spill").
But it looks like there's only one kval_spill and kvall_spill_inner in each form, so there's no need to use .each(). You can get rid of the .each() loop and just use:
var fieldShow = $(this).closest("form").find('.kval_spill_inner');
And instead of
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
you can write:
fieldShow.find('.q_value_1').val(q_value_fixed);
fieldShow.find('.q_tap_1').val(q_tap_fixed);

ng-model not updating with input from textbox

This seems like a weird one to me. I have a form for adding vets to a dog walkers' database. I've used ng-model on each field in the form.
<div class="container-fluid" ng-show="nav.page == 'new'" ng-controller="dataController as data">
<div class="row" ng-show="nav.tab == 'vet'">
<div class="col-md-2">
</div>
<div class="col-md-8">
<h1>Add a Vet</h1>
<hr />
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name..." ng-model="data.creator.vet.Name"/>
</div>
<div class="form-group">
<input type="Text" class="form-control" placeholder="Address..." ng-model="data.creator.vet.Address"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="Phone Number..." ng-model="data.creator.vet.Phone"/>
</div>
<div class="form-group">
<button class="btn btn-success" ng-click="data.newVet()">Submit</button>
</div>
</form>
</div>
<div class="col-md-2">
</div>
</div>
</div>
Yesterday it was working fine, today it won't update data.creator.vet when I input data. For the life of me, I can't see any problems with it.
The js:
app.controller('dataController', function($http) {
dataCon = this;
this.creator = {};
this.creator.client = {};
this.creator.vet = {};
this.creator.client.Dogs = [];
this.allData = {};
this.newVet = function(){
console.log("New Vet Creating....")
console.log(dataCon.creator)
vet = JSON.stringify(dataCon.creator.vet);
console.log(vet);
$http.get(SERVICE_URL + "?fn=vetCreate&vet=" + vet).then(function(response) {
dataCon.init();
});
}
});

How to change id value iterating by class

I have this html:
<div class="info">
<div class="form-group">
<label class="control-label col-sm-2">Title</label>
<div class="col-xs-10 col-sm-8">
<input id="titleInfo" class="form-control" type="text" placeholder="Title">
</div>
<div class="col-xs-1 col-sm-1">
<button class="btn btn-default remove_field"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Text</label>
<div class="col-xs-10 col-sm-8">
<textarea id="textInfo" class="form-control" type="text" placeholder="..."></textarea>
</div>
</div>
</div>
Into my jsp I have many of this:
<div class="info">
...
</div>
<div class="info">
...
</div>
<div class="info">
...
</div>
Now, I would change the id tags: titleInfo and textInfo of every div with class info in ascending order.
<div class="info">
..<input id="titleInfo1"..
..<textarea id="textInfo1"..
</div>
<div class="info">
..<input id="titleInfo2"..
..<textarea id="textInfo2"..
</div>
<div class="info">
..<input id="titleInfo3"..
..<textarea id="textInfo3"..
</div>
and so on.
I thought to iterate by class info:
var x = 1;
$(".info").each(function() {
//Now, I don't know how to change the ids
x++;
});
You need to update the code to following
var x = 1;
$(".info").each(function() {
var elems = $(this).find(".form-control"); // get all the input elements with class form-control
elems.each(function() { // iterate over the elements
$(this).attr("id", $(this).attr("id") + x); // update id
});
x++;
});
Update
var x = 1;
$(".info").each(function() {
var elems = $(this).find(".form-control"); // get all the input elements with class form-control
$(elems[0]).attr("id", "titleInfo" + x);
$(elems[1]).attr("id", "textInfo" + x);
x++;
});
You should really do this server side, within the loop control you have that generates those blocks. For the sake of answering, here you go.
$(".info").each(function(index) {
var $title = $(this).find("#titleInfo");
var $text = $(this).find("#textInfo");
$title[0].id += (index+1);
$text[0].id += (index+1);
});
Take a look at this demo as well.
Find the below code snippet.
var x = 1;
$(".info").each(function() {
var ele=$(this).find('.form-control');
ele.each(function(){
setId($(this),x)
})
x++;
});
function setId(ele,x){
ele.attr('id',ele.attr('id')+x)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="info">
<div class="form-group">
<label class="control-label col-sm-2">Title</label>
<div class="col-xs-10 col-sm-8">
<input id="titleInfo" class="form-control" type="text" placeholder="Title">
</div>
<div class="col-xs-1 col-sm-1">
<button class="btn btn-default remove_field"><i class="fa fa-remove"></i></button>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Text</label>
<div class="col-xs-10 col-sm-8">
<textarea id="textInfo" class="form-control" type="text" placeholder="..."></textarea>
</div>
</div>
</div>
This also does the same.
Script
var x = 1;
$(".info").each(function() {
var ele=$(this).find('.form-control');
ele.each(function(){
$(this).attr('id',$(this).attr('id')+x)
})
x++;
});

AngularJS push data into an object array, but show a default element if the object array is empty

There is most likely a simple solution to my question, but Im new to angularJS. What I'm doing is adding new form to DOM with a "add new button". This works fine, but if there is no data to iterate through with ng-repeat, i need to show one default form.How can this be achieved?
Here is my code:
feeCollectCtrl.addMoreFees = function () {
if (!feeCollectCtrl.feeCollectData.fees) {
feeCollectCtrl.feeCollectData.fees = [];
}
feeCollectCtrl.feeCollectData.fees.push({
"id": null,
"paymentName": "",
"fee": "",
"deadlineDate": ""
});
};
and the html is:
<ul class="list-unstyled">
<li data-ng-repeat="fee in feeCollectCtrl.feeCollectData.fees" class="feecollection-item" ng-form="feeCollectForm">
<div data-ng-if="!fee.paymentName"> {{'Payment ' + ($index +1)}}</div>
<div data-ng-if="fee.paymentName"><b>The Fee for {{fee.paymentName}} is ${{fee.fee | number:2}}</b> To change, input a new charge below.</div>
<div class="panel panel-default">
<div class="panel-body fee-panel">
<div class="form-group form-horizotal" data-ng-class="{ 'has-error': feeCollectForm.paymentName.$invalid && feeCollectForm.paymentName.$touched}">
<label for="paymentName" class="col-sm-3 control-label">Payment Name</label>
<div class="col-sm-8">
<input type="text" required="required" data-ng-model="fee.paymentName" maxlength="50" class="form-control" name="paymentName" id="paymentName" placeholder="Payment Name">
<div data-ng-if="feeCollectForm.paymentName.$touched" data-ng-messages="feeCollectForm.paymentName.$error">
<span class="help-block" data-ng-message="required">required field</span>
</div>
</div>
</div>
<div class="form-inline col-xs-12">
<div class="col-xs-2"></div>
<div class="col-xs-10">
<div class="form-group fee-amount" data-ng-class="{ 'has-error': feeCollectForm.fee.$invalid && feeCollectForm.fee.$touched}">
<label for="fee" class="control-label">Fee</label>
<span class="currencySpanFees">$</span>
<valid-number name="fee" required="required" id="fee" data-ng-model="fee.fee" placeholder="Fee Amount" cssclass="form-control currencyInput" />
<div data-ng-if="feeCollectForm.fee.$touched" data-ng-messages="feeCollectForm.fee.$error">
<span class="help-block" data-ng-message="required">required field</span>
</div>
</div>
<div class="form-group fee-deadline" data-ng-class="{ 'has-error': feeCollectForm.deadlineDate.$invalid && feeCollectForm.deadlineDate.$touched}">
<label for="deadlineDate" class="control-label">Deadline</label>
<div class="input-group">
<input name="deadlineDate" id="deadlineDate" type="text" class="form-control" show-button-bar="true" datepicker-popup="{{format}}" ng-model="fee.deadlineDate" is-open="fee.opened" min-date="minDate" datepicker-options="dateOptions" date-disabled="disabled(date, mode)" required="required" close-text="Close" ng-change="feeCollectCtrl.validateDate('deadlineDate',feeCollectForm.deadlineDate.$viewValue)" ng-keyup="feeCollectCtrl.validateDate('deadlineDate',feeCollectForm.deadlineDate.$viewValue)" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event, $index)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
<div data-ng-if="feeCollectForm.deadlineDate.$touched" data-ng-messages="feeCollectForm.deadlineDate.$error">
<span class="help-block" data-ng-message="required">required field</span>
</div>
</div>
</div>
</div>
<span class="delete-fee pull-right" data-ng-click="feeCollectCtrl.removeFees($index)"><i class="fa fa-trash-o"></i> delete</span>
</div>
</div>
</li>
</ul>
You could something like:
<li ng-show=feeCollectCtrl.feeCollectData.fees.length===0">
<--! place your default form here -->
</li>
<li data-ng-repeat="fee in feeCollectCtrl.feeCollectData.fees" class="feecollection-item" ng-form="feeCollectForm"> ....
The first li will only be shown when the array is empty. In any case you should place the form outside the ng-repeat.
The best solution I found was to push() the elements during the GET request. So in the GET we check if there are any objects, if not we call the push function like this:
GET request:
var processFeeData = function (data) {
originalResetData = angular.copy(data);
feeCollectCtrl.feeCollectData = data;
if (feeCollectCtrl.feeCollectData.fees && feeCollectCtrl.feeCollectData.fees.length) {
for (var i = 0; i < feeCollectCtrl.feeCollectData.fees.length; i++) {
var temp = new Date(feeCollectCtrl.feeCollectData.fees[i].deadlineDate);
feeCollectCtrl.feeCollectData.fees[i].deadlineDate = formatDate(new Date(temp.getTime() + temp.getTimezoneOffset() * 60000));
}
} else {
// Here I am calling the push() Function
feeCollectCtrl.addMoreFees();
}
setFormPristine();
};
feeCollectCtrl.get_fees_data = function (url) {
serverFeesUpload.get(url).then(function (data) {
processFeeData(data);
});
};
Push Function
feeCollectCtrl.addMoreFees = function () {
if (!feeCollectCtrl.feeCollectData.fees) {
feeCollectCtrl.feeCollectData.fees = [];
}
feeCollectCtrl.feeCollectData.fees.push({
"id": null,
"paymentName": "",
"fee": "",
"deadlineDate": ""
});
};

Categories