add and delete json list inside ng-repeat - javascript

i want to create a page where someone adds 1 or more locations to a contact and right now i have something that looks like this.
<div class="input-append" ng-repeat="location in newPartner.partner_location">
<input class="input-large" type="text" ng-model="location">
<button class="btn" type="button" ng-click="delLocation1({{$index}})">- {{$index}}</button>
</div>
<div class="input-append">
<input class="input-large" type="text" ng-model="new_location">
<button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
</div>
This is the HTML and the controller looks like this.
$scope.newPartner = {'partner_name':'newname','partner_location':['X','Y','Z']};
$scope.addLocation1 = function() {
$scope.newPartner.partner_location.push($scope.new_location);
$scope.new_location = "";
}
$scope.delLocation1 = function(id) {
$scope.newPartner.partner_location.splice(id, 1);
}
Now it works great on begin but if i delete some items and add some it suddenly bugs out and starts to delete the previous item instead the one i press - (minus) on.
Is there something i did wrong? Thank you in advance, Daniel!

First off remove {{}} from ng-click="delLocation1({{$index}})". It should be:
ng-click="delLocation1($index).
Second, I suggest you to add some basic debugger to see what happens with our model when we add new value: <pre>{{newPartner.partner_location|json}}</pre>
Third, I would change the model to:
$scope.newPartner = {
'partner_name': 'newname',
'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
};
because, by this way: ['X','Y','Z'] we can't modify our data.
Demo Fiddle
Finally this is our fixed code:
HTML
<div ng-controller="fessCntrl">
<div ng-repeat="location in newPartner.partner_location">
<input class="input-large" type="text" ng-model="location.value">
<button class="btn" type="button" ng-click="delLocation1(newPartner.partner_location, $index)">{{$index}}</button>
</div>
<div class="input-append">
<input class="input-large" type="text" ng-model="new_location">
<button class="btn btn-primary" type="button" ng-click="addLocation1()">+</button>
</div>
<pre>{{newPartner.partner_location|json}}</pre>
</div>
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.new_location = "empty";
$scope.newPartner = {
'partner_name': 'newname',
'partner_location': [{value:'X'}, {value:'Y'}, {value:'Z'}]
};
$scope.addLocation1 = function () {
$scope.newPartner.partner_location.push({value:$scope.new_location});
$scope.new_location = "empty";
}
$scope.delLocation1 = function (locations, index) {
locations.splice(index, 1);
}
});
fessmodule.$inject = ['$scope'];

Related

TypeError: $scope.lstLaptop.push is not a function

I'm trying to make a simple form for insert, delete, update using localStorage to store my data. When I click Add button, It shows an error
TypeError: $scope.lstLaptop.push is not a function.
I was back to my code and check syntax if I'm wrong, but I think my code was only 3 lines and look usual. Can you tell me what I was missing something or what the problem really was from?
Just ignored my other code and check my controller lapCreateUpdateCtrl please, I'm out of idea what I'm wrong.
HTML file:
<div class="container">
<table class="table table-hover">
<tr>
<th>Laptop Model</th>
<th>Price($)</th>
<th>Option</th>
</tr>
<tr ng-repeat = "laptops in lstLaptop track by $index">
<td><p ng-bind = laptops.model></p></td>
<td><p ng-bind = laptops.price></p></td>
<td><button type="button" ng-click="remove1($index)"
class="btn btn-danger btn-xs">
Delete
</button>
<button type="button" ng-click="edit1($index)"
class="btn btn-warning btn-xs">
Edit
</button>
<button type="button" ng-click="update1($index)"
class="btn btn-info btn-xs">
Update
</button>
</td>
</tr>
</table>
<button type="button" class="btn btn-success btn-sm"
ng-click="save()">
Save
</button>
</div>
</div>
</body>
app.JS file:
routerApp.controller('lapCreateUpdateCtrl', ["$scope", function($scope){
$scope.laptop = {};
$scope.lstLaptop = [];
function init(){
var strLaptop = window.localStorage.getItem("LAPTOP_KEY");
if(strLaptop){
$scope.lstLaptop = JSON.parse(strLaptop);
}
}
init();
$scope.add1 = function(){
$scope.lstLaptop.push($scope.laptop);
$scope.laptop = {};
}
$scope.remove1 = function(index){
$scope.lstLaptop.splice(index,1);
alert("Deleted!");
}
$scope.edit1 = function(index){
$scope.laptop = angular.copy($scope.lstLaptop[index]);
}
$scope.update1 = function(index){
$scope.lstLaptop.splice(index, 1, $scope.laptop);
$scope.laptop = {};
}
$scope.save=function(){
window.localStorage.setItem("LAPTOP_KEY", JSON.stringify($scope.lstLaptop));
}
}]);
I want content input from textbox
<input type="text" ng-model="laptop.model" id="model" name="model"
placeholder="Model" required />
<input type="number" ng-model="laptop.price" id="price" name="price"
placeholder="Price" required />
<button type="button" ng-click="add()">
Add Desktop
</button>
You have called init() and then inside that function, you have changed the $scope.lstLaptop to an object. When $scope.add1 will be called, it will throw an error as object does not have push function. It only works with Arrays.
I don't understand what you want to achieve, but you can do something like below. It will retain the lstLaptop as array
function init(){
var strLaptop = window.localStorage.getItem("LAPTOP_KEY");
if(strLaptop){
$scope.lstLaptop.push(JSON.parse(strLaptop));
}
}

Add items to list in angular

I have the following to create a job with a position and multiple requirements Plunker example:
<div ng-controller="MainCtrl as vm">
<div>Position: <span data-ng-bind="vm.job.position"></span></div>
<br/>
<form name="form" data-ng-submit="vm.create(job)">
<label for="position">Enter the Position</label>
<input id="position" name="vm.job.position" type="text" data-ng-model="vm.job.position" />
<div>
<br/>
Requirements:
<br/>
<ul>
<li data-ng-repeat="r in vm.job.requirements">{{r.name}}</li>
</ul>
<input id="name" name="requirement.name" type="text" data-ng-model="requirement.name" />
<input type="button" value="Add Requirement" class="button" data-ng-click="vm.addRequirement(requirement)"/>
</div>
<br/><br/>
<button>Create Job</button>
</form>
</div>
the controller
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.job = { position: '', requirements: [] };
vm.create = function (job) {
alert("job created");
}
vm.addRequirement = function (requirement) {
vm.job.requirements.push(requirement);
}
});
When I add a requirement I see it on the list but when I try to add a new one, the one that is already in the list start to change. I do not want that. I want to add a new one to the list.
Finally, when I submit the form using "Create Job" is where I will send all the Job data to the API.
The problem is with your addRequirement function, because you are adding the same object to the list (and that's the reason your item changes the name when you edit the input box).
To make your example work as intended you should push a clone of the requirement object (see documentation).
vm.addRequirement = function (requirement) {
vm.job.requirements.push( angular.copy(requirement) );
}
The easiest way to do this, is simply use ng-model on the input that you would like to append to your list. Then you can easily access it from the controller.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var vm = this;
vm.job = { position: '', requirements: [] };
function create(job) {
alert("job created");
}
function addRequirement() {
vm.job.requirements.push(vm.currentRequirement);
}
vm.create = create;
vm.addRequirement = addRequirement;
});
and in the html:
<input type="button" value="Add Requirement" ng-click="vm.addRequirement()"/>

Form data not showing after post in AngularJS

I am trying to post a form data but the content are not updated on the UI.
The following code is working it does post the data but the tags are not updated in the {{tag.Title}}.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var new1 = data;
$scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
<div class="row" data-ng-repeat="tagsByType in consultantCv.TagsbyTypes" ng-init="init('tag',2000)">
<div class="col-md-12">
<hr />
<h2>
<i class="icons8-{{tagsByType.CssClass}}" aria-hidden="true"></i>{{tagsByType.Title}}
</h2>
<div class="tags">
<div class="input-group" ng-controller="consultantController">
<div ng-repeat="tag in tagsByType.Tags" class="tag label label-success">
{{tag.Title}}
<a class="close" href ng-click="removeTag(tag)">×</a>
</div>
<form ng-submit="saveTag(Title,tagsByType.Id)" role="form">
<input type="text" ng-model="Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>
</div>
</div>
</div>
</div>
Push your data as object with same property name.
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(data){
var newData = {
Title : data,
}
$scope.consultantCv.TagsbyTypes[0].Tags.push(newData);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag); //this code is not updating the binding in the UI
};
Found the issue was that tagsType was not passed to the controller.
Fixed it by the following code
$scope.saveTag = function (data,TagTypeId) {
var result = employeeCvService.addTag(data, TagTypeId, $scope.consultantCv.Id).success(function(result){
TagTypeId.Tags.push(result);
$scope.consultantCv.TagsbyTypes.Tags.push(newData);
//$scope.consultantCv.TagsbyTypes[0].Tags.push(new1);
});
// $scope.consultantCv.TagsbyTypes[0].Tags.push(newtag);
};
<form ng-submit="saveTag(tag.Title,tagsByType)" role="form">
<input type="text" ng-model="tag.Title" class="form-control" placeholder="add a tag..." ng-options="suggestion.Title for suggestion in suggestion" uib-typeahead="suggestion.Title for suggestion in loadTags($viewValue,tagsByType.Id)" typeahead-loading="loadingTags" typeahead-no-results="noResults">
<span class="input-group-btn"><input type="submit" class="btn btn-default" value="Add"></span>
</form>

Angular $setPristine is not working

Html :
I'm using controller as syntax.
<form name="occupantDetailForm" role="form" novalidate class="form-validation">
<div class="form-group form-md-line-input form-md-floating-label no-hint">
<input class="form-control" type="text" name="LastName" ng-model="vm.occupantDetail.lastName" ng-class="{'edited':vm.occupantDetail.lastName}" maxlength="#OccupantDetail.MaxLength" required>
<label>#L("LastName")</label>
</div>
<button type="submit" class="btn btn-primary blue" ng-click="vm.saveOccupantDetail(occupantDetailForm)" ng-disabled="occupantDetailForm.$invalid"><i class="fa fa-save"></i> <span>#L("Save")</span></button>
</form>
JS :
vm.saveOccupantDetail = function (form) {
vm.occupantDetailForm = form;
createOrEditOccupantDetail();//create or edit
vm.occupantDetail = {};
vm.occupantDetailForm.$setPristine();
}
Q : I have tried many ways but it is not working ? When I use the vm.occupantDetailForm.$setUntouched(); then it works fine.But then the problem is Save button is not being disabled.Could you tell me why ? When I use the vm.occupantDetailForm.$setPristine(); only then it is not working at all.Why ? Thanks.
$setPristine only marks your form as $pristine and to actually reset the form you need, set your model to a new object.
A better explanation is given here in the link:
$setPristine not working
Below is some code which might help you:
<div ng-app="myapp">
<div ng-controller="UserCtrl">
<form name="user_form" novalidate>
<input name="name" ng-model="user.name" placeholder="Name" required/>
<button class="button" ng-click="reset()">Reset</button>
</form>
<p>
Pristine: {{user_form.$pristine}}
</p>
</div>
</div>
Controller Code:
var app = angular.module('myapp', []);
function UserCtrl($scope) {
$scope.reset = function() {
$scope.user = {};
$scope.user.name = "";
$scope.user_form.$setPristine();
$scope.user = {};
}
}
A fiddle:
http://jsfiddle.net/p7e1nway/1/
Update:, can you try setting $submitted to false
$scope.occupantDetailForm.$setPristine();
$scope.occupantDetailForm.$setUntouched();
$scope.occupantDetailForm.$submitted = false;

How to add value to ng-model in Angularjs

How to add value to ng-model in angularjs. my html is:
<textarea rows="5" ng-model="comment.comment_text"></textarea>
<input type="hidden" ng-model="comment.task_id" value="{{task.id}}">
<input type="hidden" ng-model="comment.user_id" value="{{profile.id}}">
<button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>
and angular controller:
$scope.create = function(comment) {
console.log(comment);
};
when click on button show result in console:
{comment_text: "test"}
BUT I want to show like this:
{comment_text: "test", user_id:1 ,task_id:53}
On your controller's constructor you should definitely instantiate the initial value of your 'comment' variable using:
$scope.comment = $scope.comment || {
user_id: 'amcpanaligan',
comment_text: 'sample'
//// other object property declaration goes here...
};
value={{someValue}} does not make sense.
You should use only ng-model for text input hidden
function Ctrl($scope) {
$scope.task = {
id: 1
}
$scope.create = function(comment) {
comment.taskId = $scope.task.id;
console.log(comment);
};
}
<div ng-app="">
<div ng-controller="Ctrl">
<textarea rows="5" ng-model="comment.comment_text"></textarea>
<input type="hidden" ng-model="task.id">
<button type="submit" class="btn btn-success" ng-click="create(comment)">Send</button>
</div>
</div>
see fiddle

Categories

Resources