AngularJS select not updating after json push - angularjs

I have the following controller:
function userControl($scope,$http) {
$scope.users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
]
$scope.addUser = function() {
var nextid = $scope.getNextId();
$scope.users.push({id:nextid,name:$scope.userName});
$scope.userName = '';
//$apply();
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
And the following HTML:
<h2>Users</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div ng-controller="userControl">
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
When I add a user in the addUser() function I can see the user is added since it's listed under the ng-repeat, however the user name does not appear in the select box.

This is because you use the same controller twice. This creates two separate scopes. When you add a user in one scope it doesn't get added in the second scope. The fix is simple, join the code in one scope:
<div ng-controller="userControl">
<h2>Users</h2>
<div>
<div ng-repeat="user in users">
{{user.id}} : {{user.name}}
</div>
<form ng-submit="addUser()">
<input type="text" ng-model="userName" placeholder="User Name" />
<input type="submit" value="add">
</form>
</div>
<h2>Add role to user</h2>
<div>
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users"></select>
<input type="submit" value="add">
</form>
</div>
</div>
An alternative approach is to create a Service since services are singletons:
module.factory('Users',function(){
var users = [
{"id":"0","name":"User1","roles":[{}]},
{"id":"1","name":"User2","roles":[{}]},
];
return {
users:users,
add:function(user){
users.push(user);
}
}
});
function userControl($scope, Users) {
$scope.users = Users.users;
$scope.addUser = function() {
var nextid = $scope.getNextId();
Users.add({id:nextid,name:$scope.userName});
$scope.userName = '';
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
This will work with your original markup.

Related

angular form ng-repeat deleting single form

i am working with dynamic forms with ng-repeat .i am getting dynamic forms according to my userid. each form has delete button. my requirement is once i am clicking delete button i need to delete that particular form and those values from my user obj and remaining values i need to send to server. in this example i want to delete id 2 (2nd form), and 1st and 2nd form data i need to store one variable.
please send some fiddle for this .
my html code
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<select ng-model="user.location" ng-options="v for v in locations" ng-init='initLocation(user)' name="select2" required>
</select>
</div>
<div>
<button>delete</button>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>
js file
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: ""
};
});
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.initLocation = (user) => {
$timeout(() => {
user.location = $scope.locations[0];
});
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
As per your requirement i am adding ng-click to delete button and adding removeSelForm method and pass your user object into that function parameter. in controller i am removing that particular form values from users object.
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope, $timeout) {
$scope.ids = [1, 2, 3];
$scope.users = $scope.ids.map(function(id) {
return {
id: id,
comment: "",
location: ""
};
});
$scope.locations = ['india', 'usa', 'jermany', 'china', 'Dubai'];
$scope.initLocation = (user) => {
$timeout(() => {
user.location = $scope.locations[0];
});
}
$scope.removeSelForm = function(item) {
var index = $scope.users.indexOf(item)
$scope.users.splice(index, 1);
}
$scope.adduser = function() {
var data = $scope.users.map(function(user) {
return {
"userid": user.id,
"manualcomment": user.comment,
"location": user.location
}
});
console.log("data", data)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<form role="form" name='userForm' novalidate>
<div class="container">
<div class="row" ng-repeat="user in users">
<div class="form-group">
<div class="col-md-3">
<label>ID</label>
<input ng-model="user.id" id="user.id" name="user.id" placeholder="Enter bugid" type="text" required readonly disabled>
</div>
<div class="col-md-3">
<label>Comments</label>
<textarea ng-model="user.comment" id="textarea1" rows="1" required></textarea>
</div>
<div class="col-md-3 ">
<label>Location</label>
<select ng-model="user.location" ng-options="v for v in locations" ng-init='initLocation(user)' name="select2" required>
</select>
</div>
<div>
<button ng-click="removeSelForm(user)">delete</button>
</div>
</div>
</div>
</div>
<div class="buttonContainer text-center btn-container">
<br>
<button ng-disabled="userForm.$invalid" type="button" id="adduser" ng-click="adduser()">Add user</button>
<button type="button" class="btn button--default btn--small pull-center">Close</button>
</div>
</form>
</div>

angularjs dynamic form field inside ng-repeat

Hi I have problem in adding form field and binding inside the ng-repeat
my form is like this
<div ng-repeat="(key, value) in categories">
<div class="col-sm-12"><b>{{ value.name }}</b></div>
<div class="col-sm-12" >
<div class="col-sm-3">
<label>Product</label>
<input
type="text"
class="form-control input-sm"
ng-model="product.name">
</div>
<div class="col-sm-1">
<label> </label>
<button type="button" ng-hide="$first" ng-click="removeProduct()">-</button>
</div>
</div>
<div class="col-sm-1">
<button type="button" ng-click="addNewProduct()">+</button>
</div>
</div>
json categories
[{"id":1,"name":"Furniture & Fixture"},
{"id":2,"name":"Miscellaneous Property"},
{"id":3,"name":"Office Equipment"},
{"id":4,"name":"Renovation"},
{"id":5,"name":"Vehicle"}]
Here I want to add dynamic form fields(products) for each category
my js is like this
$scope.addNewProduct = function(){
$scope.categories.push({});
}
$scope.removeProduct= function(index){
$scope.categories.splice(index,1);
}
i know its won't work i need to push data to each category.please help
Your function for adding new category should look like this:
$scope.addNewProduct = function(){
var newCategory=
{
id:$scope.categories.length+1,
name:$scope.product.name
}
$scope.categories.push(newCategory);
}
Following code will demo how to append 'item' to items list:
<script>
angular.module('AddItemToList', [])
.controller('FormController', ['$scope', function($scope) {
$scope.item = '';
$scope.items = [];
$scope.submit = function() {
if (typeof($scope.item) != "undefined" && $scope.item != "") {
// append item to items and reset item
$scope.items.push($scope.item);
$scope.item = '';
}
};
}]);
</script>
<form ng-submit="submit()" ng-controller="FormController">
Input item and Submit the form. This will get appended to the list:
<input type="text" ng-model="input" name="item" />
<input type="submit" id="submit" value="Submit" />
<pre>Final List={{items}}</pre>
</form>

Can't get option value when using Angularjs

I have the following AngularJS code:
angular.module('loggedInApp', ['ui.bootstrap']);
var myapp = angular.module('loggedInApp', ['ui.bootstrap'])
myapp.controller('AddParentController', function ($scope, addParentService) {
var vm = this;
$scope.addParentService = addParentService;
$scope.setName = function (val) {
addParentService.inputParentName = val;
}
$scope.setEmail = function (val) {
addParentService.inputParentEmail = val;
}
$scope.setCarrier = function (val) {
addParentService.inputParentCarrier = val;
}
$scope.setBirthday = function (val) {
addParentService.inputParentBirthday = val;
}
});
myapp.service('addParentService', function () {
var vm = this;
vm.eventObjs = [];
vm.parent = [];
vm.addParent = function () {
alert(vm.inputParentName);
alert(vm.inputParentBirthday);
alert(vm.inputParentEmail);
alert(vm.inputParentCellPhone);
alert(vm.inputParentCarrier);
vm.parent.push({
name: vm.inputParentName, dob: vm.inputParentBirthday,
cell: vm.inputParentCellPhone, carrier: vm.inputParentCarrier,
email: vm.inputParentEmail, active: true, personId: vm.parent.length + 1
});
vm.inputParentName = '';
vm.inputParentDOB = '';
vm.inputParentCellPhone = '';
vm.inputParentCarrier = 0;
vm.inputParentEmail = '';
vm.active = true;
};
vm.buildEventObject = function (titleValue, startValue, personId, choreIdValue) {
vm.eventObjs.push({ title: titleValue, start: startValue, familymemberpersonid: personId, choreId: choreIdValue });
return vm.eventObjs;
}
vm.returnEventObject = function () {
return vm.eventObjs;
}
});
My HTML looks like this:
<div class="row clearfix" ng-controller="AddParentController as parent">
<div class="col-md-6 column">
<form role="form" ng-submit="addParentService.addParent()">
<div class="form-group">
<label for="inputParentName">Name</label><input class="form-control" id="inputParentName" value="" type="text" ng-model="addParentService.inputParentName" />
</div>
<div class="form-group">
<label for="inputParentBirthday">Birthday</label><input class="form-control" id="inputParentBirthday" value="" type="text" ng-model="addParentService.inputParentBirthday" />
</div>
<div class="form-group">
<label for="inputParentCellPhone">Cell Phone</label><input class="form-control" id="inputParentCellPhone" value="" type="text" ng-model="addParentService.inputParentCellPhone" />
</div>
<div class="form-group">
<label for="inputParentCarrier">Phone Carrier</label><br />
<select class="form-control" id="inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
</div>
<div class="form-group">
<label for="inputParentEmail">E-Mail Address</label><input class="form-control" id="inputParentEmail" value="" type="email" ng-model="addParentService.inputParentEmail" />
</div>
<button class="btn btn-default" type="submit">Submit</button>
</form>
</div>
<br /><br />
<div class="col-md-6 column">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Parent:
</h3>
</div>
<div class="panel-body">
<table class="table table-striped">
<tr>
<th>Name</th>
<th>Cell #</th>
<th>E-Mail</th>
<th>DOB</th>
</tr>
<tr ng-repeat="parent in addParentService.parent">
<td>{{parent.name}}</td>
<td>{{parent.cell}}</td>
<td>{{parent.email}}</td>
<td>{{parent.dob}}</td>
</tr>
</table>
</div>
<div class="panel-footer">
<button class="btn btn-default" type="submit">Save your Family!</button>
</div>
</div>
</div>
</div>
My issue is when I click the submit button I am calling my service that alerts out all the different values I entered. Everything works except the inputParentCarrier value. When it alerts out it says 'undefined'
Seems like this should be an easy fix, but right now I can't see what is wrong.
You are missing ng-model on your select
<select class="form-control" id="inputParentCarrier" ng-model="addParentService.inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
You need to add ng-model="addParentService.inputParentCarrier" to your select tag
you need to add model for select element as well, like:
<select ng-model="addParentService.inputParentCarrier" class="form-control" id="inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
You should bind your ng-model to the select, not the label.
<select class="form-control" id="inputParentCarrier" ng-model="addParentService.inputParentCarrier">
<option>ATT</option>
<option>Cricket</option>
<option>Sprint</option>
<option>T-Mobile</option>
<option>Verizon</option>
</select>
change your select tag to this:
<select class="form-control" id="inputCarrier" ng-model="myService.inputParentCarrier">
<option value="att">ATT</option>
....
<select>

Fields values generated using ng-repeat is not getting while submit

Template for form submission. This page will display the form template. Initially it shows the TItle,Full Name. On clicking the 'Add Tags' link new input fields is been generated for entering tags.
On submit, the field input(story.tag) is not been included on RequestPayload
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-controller="Note" >
<div ng-repeat="story in items ">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" id="tag" required/>
</div>
<a ng-click="add()">Add Tags</a>
</div>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
script :- app.js
angular.module("getbookmarks", ["ngResource"])
.factory('Story', function ($resource) {
var Story = $resource('/api/v1/stories/:storyId', {storyId: '#id'});
Story.prototype.isNew = function(){
return (typeof(this.id) === 'undefined');
}
return Story;
})
.controller("StoryCreateController", StoryCreateController);
function StoryCreateController($scope, Story) {
$scope.story = new Story();
$scope.save = function () {
$scope.story.$save(function (story, headers) {
toastr.success("Submitted New Story");
});
};
}
//add dynamic forms
var Note = function($scope){
$scope.items = [];
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
};
}
The story object inside ng-repeat is in another scope. This JSFiddle should do what you are looking for.
<div ng-app>
<div ng-controller="NoteCtrl">
<form novalidate ng-submit="save()">
<div>
<label for="title">Title</label>
<input type="text" ng-model="story.title" id="title" required/>
</div>
<div>
<label for="firstName">Full Name</label>
<input type="text" ng-model="story.fullname" id="fullname" required/>
</div>
<div ng-repeat="story in items">
<label>Tag {{$index+1}}:</label>
<input type="text" ng-model="story.tag" required/>
</div> <a ng-click="add()">Add Tags</a>
<button id="save" class="btn btn-primary">Submit Story</button>
</form>
<div ng-repeat="test in items">
<label>Tag {{$index+1}}: {{test.tag}}</label>
</div>
</div>
</div>
The NoteController:
function NoteCtrl($scope) {
$scope.story = {};
$scope.items = [];
$scope.story.tag = $scope.items;
$scope.add = function () {
$scope.items.push({
inlineChecked: false,
tag: "",
questionPlaceholder: "foo",
text: ""
});
console.log($scope.story);
};
}

Angular Form not submitting on first click

I have built a small angular App into my website whereby a user enters a searchterm into an input field and then values are returned via an Angular service. When I attempt to submit a value however, the form does not submit and will only submit on the 2nd attempt. I cannot figure out why this is happening.
Here is my code:
<div ng-app="clubFilter" class="col-lg-12">
<div class="col-lg-3">
</div>
<div class="col-lg-9" ng-controller="clubController">
<form ng-submit="filterClubs()">
<input type="text" name="location" ng-model="searchTerm" placeholder="Search..." />
<input type="submit" name="submit" value="Submit" />
</form>
<ul class="leisure-centres">
<li ng-repeat="club in clubs">
<div class="centre">
<a class="link" ng-href="{club.link}">More info</a>
<div class="image" ng-show="club.image > 0">
<img src="{{image}}" alt="{{club.title}}" />
</div>
<div class="details">
<div class="title">
<h3>{{club.title}}<span ng-show="club.distance > 0"> - {{club.distance}} miles away</span></h3>
</div>
<div class="address">
{{club.building}},
{{club.street}},
{{club.city}},
{{club.county}},
{{club.postcode}}
</div>
<div class="tel">
<strong>Tel: </strong>
</div>
<div class="email">
<strong>Email: </strong>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
var JSONItems = <?php echo $this->JSONItems; ?>;
var searchTerm = "<?php echo $this->searchTerm; ?>";
And here is my angular controller
angular.module('clubFilter.controllers', []).
controller('clubController', function($scope, $http, googleMapService) {
$scope.keyWord = "SEARCH";
$scope.clubsJSON = JSONItems;
if(searchTerm == "") {
$scope.clubs = $scope.clubsJSON;
} else {
$scope.searchTerm = searchTerm;
googleMapService.setLatLng($scope.searchTerm, $scope.clubsJSON).then(function(sortedArray) {
$scope.$apply(function() {
$scope.clubs = sortedArray;
});
}, function(err) {
alert("no");
});
}
$scope.filterClubs = function() {
googleMapService.setLatLng($scope.searchTerm, $scope.clubsJSON).then(function(sortedArray) {
$scope.clubs = sortedArray;
}, function(err) {
alert("no");
});
}
});
As far as I am aware I have everything defined as it should be?
Thanks
Try this one;
<div class="col-lg-9" ng-controller="clubController as club">
<form ng-submit="club.filterClubs()">
<input type="text" name="location" ng-model="club.searchTerm" placeholder="Search..." />
<input type="submit" name="submit" value="Submit" />
</form>
And in your controller;
this.filterClubs = function() {
googleMapService.setLatLng(this.searchTerm, $scope.clubsJSON).then(function(sortedArray) {
$scope.clubs = sortedArray;
}, function(err) {
alert("no");
});
}

Resources