Can't get option value when using Angularjs - 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>

Related

How to Increment Dynamic field ngModel name in Angularjs..?

Here when i click Add Product Button it creates a text field. But I want to create create different name for each text box in ng-model="column.product_cgst".
like column.product_cgst-1, column.product_cgst-2.
<form>
<div ng-repeat="column in columns" style="margin-bottom: 10px;">
<div class="form-group">
<input type="text" name="product_name" ng-model="column.product_name" required placeholder="Product Name" class="form-control"
id="userName">
</div>
<div class="form-group">
<select name="units" ng-model="column.units" class="form-control">
<option value="">Select Units</option>
<option ng-repeat="units in allunits" value="{{units.unit_id}}">
{{units.unit_name}}
</option>
</select>
</div>
<div class="form-group">
<input id="cgst" type="text" ng-model="column.product_cgst" placeholder="Enter CGST" required class="form-control">
</div>
<div class="form-group">
<input id="sgst" type="text" ng-model="column.product_sgst" placeholder="Enter SGST" required class="form-control">
</div>
<div class="form-group">
<input id="igst" type="text" ng-model="column.product_igst" placeholder="Enter IGST" required class="form-control">
</div>
<button class="remove btn-sm btn-danger" ng-click="removeColumn($index)">x</button>
</div>
<div class="form-group text-right m-b-0">
<button class="btn btn-primary waves-effect waves-light" type="submit">
Submit
</button>
<button class="addfields btn btn-info waves-effect waves-light" ng-click="addProduct()">Add Product</button>
</div>
</form>
Controller:
$scope.columns = [];
$scope.addProduct = function () {
var newItemNo = $scope.columns.length + 1;
$scope.columns.push({ 'colId': 'col' + newItemNo });
};
$scope.removeColumn = function (index) {
$scope.columns.splice(index, 1);
if ($scope.columns.length() === 0 || $scope.columns.length() == null) {
alert('no rec');
$scope.columns.push = [{ "colId": "col1" }];
}
};
You can use $index in the HTML to increment your ng-model dynamically instead of doing in controller.
Using $index in the interpolation with ngModel will not work. Try something like below
column.product_cgst[$index]
I get the Solutions here,only change in my angularjs controllers.
//Add Dynamic Column
$scope.columns = [{id: 'firstField'}];
$scope.addProduct = function(){
var newItemNo = $scope.columns.length+1;
$scope.columns.push({'id':'field'+newItemNo});
}
//Remove Dynamic Column
$scope.removeColumn = function() {
var itemLast = $scope.columns.length-1;
$scope.columns.splice(itemLast);
};
//Insert Data in Database:-
$scope.productAdd = function(){
$http.post('product/insert_product', $scope.columns)
.success(function(data){
console.log(data);
});
}

How to reset Bootstrap Form

Here im using Bootstrap validations with AngularJs when my form is submitted the columns is reset but its shows all validation..But my aim is its should not display validations
Bootstrap
<div class="modal" id="modal1">
<div class="modal-dialog">
<div class="modal-content">
<form name="f1" novalidate ng-submit="Save(Auth.emp)">
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-sm-4">
Email
</div>
<div class="col-sm-8">
<input type="text" name="email" class="form-control" ng-model="Auth.Email" ng-class="Submitted?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.email.$dirty ||Submitted) && f1.email.$error.required">Email REq</span>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-4">
Password
</div>
<div class="col-sm-8">
<input type="text" name="psw" class="form-control" ng-model="Auth.Password" ng-class="Submitted?'ng-dirty':''" required />
<span class="Error" ng-show="(f1.psw.$dirty ||Submitted) && f1.psw.$error.required">Password REq</span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="{{LoginAction}}" />
</div>
</form>
</div>
</div>
</div>
AngularCode.Js
$scope.Save = function (emp) {
if ($scope.LoginAction = "Login") {
$scope.Submitted = true;
if ($scope.isFormValid == true) {
var ss = {
Email: $scope.Auth.Email,
Password: $scope.Auth.Password,
}
var xxer = myServices.GetLogin(ss);
xxer.then(function (msg) {
$scope.msg = msg.data;
$('#modal2').modal('show')
Reset();
})
}
}
}
Reset
function Reset() {
$scope.Email = '';
$scope.Password = '';
}
I think you looking for this:
function Reset() {
$scope.Auth.Email = ''
$scope.Auth.Password = '';
}
You can set a model at the same level as the form tag and make all other inputs sub properties. Then set form model at the root level to an empty object when you click on reset. Here's a codepen.
function exampleController($scope) {
$scope.reset = function() {
$scope.form = {};
};
}
angular
.module('app', [])
.controller('exampleController', exampleController);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div class="row" ng-app="app" ng-controller="exampleController">
<form novalidate ng-model="form">
<input ng-model="form.email" type="email" />
<input ng-model="form.password" type="password" />
</form>
<button ng-click="reset()">Reset</button>
<pre>{{form}}</pre>
</div>

bootstrap table is not working properly

ok, I have a issue with my bootstrap table. I have a Employee Modal with 2 tabs. The first tab is the table with the current Employees. When you select any Employee it takes you to the 2nd tab which has the Employee details. There is a input field on top of the table that allows searching, and if the Employee is not in there by the typed name, the user can hit Enter and it takes you to the details tab to create a new entry for that Employee .When I select a Employee and it takes me to the details tab, I want to be able to go back to the table and select a new Employee if need be. problem is that Employee is a empty row on the table. i need to reopen the modal for it to reappear.
plunkr
<div class="container">
<form class="form-horizontal" ng-submit="submitEmployee()" enctype="multipart/form-data">
<tabset>
<tab heading="List" select="ClearEmployeeModalFields();">
<div class="col-xs-12" style="margin-top:20px;width:initial">
<div style="overflow: auto;height:190px;max-width:520px;min-width:520px" id="scrollAreaCustomers">
<table class="table" style="">
<tr>
<th style="font-weight: bold;">Name</th>
</tr>
<tr>
<input type="text" placeholder="New Employee" ng-model="selectedEmployee.EmployeeFirstName" ng-enter="data.static = true" />
</tr>
<tr ng-repeat="employee in employeeArray | filter:selectedEmployee.EmployeeFirstName" class="pointer">
<td ng-click="setSelectedEmployee(employee);data.static = true">{{employee.EmployeeFirstName}} {{employee.EmployeeLastName}}</td>
</tr>
</table>
</div>
</div>
<!--End col-xs-12-->
</tab>
<tab heading="Details" active="data.static">
<div class="col-xs-12" style="margin-top:20px">
<div class="inline-fields" style="">
<label style="margin-left:-11px">Employee Id:</label>
<input style="width:100px" ng-model="selectedEmployee.CompanyEmployeeId" type="text">
<label style="margin-left:100px">Email:</label>
<input style="width:150px" ng-model="selectedEmployee.EmployeeEmail" type="email">
</div>
<div class="inline-fields">
<label style="margin-left:0px">First Name:</label>
<input style="width:150px" ng-model="selectedEmployee.EmployeeFirstName" type="text">
<label style="margin-left:57px">Title:</label>
<select style="width:150px" ng-model="selectedEmployee.EmployeeTitle">
<option value="" selected="selected">Select</option>
<option value="Manager" ng-model="selectedEmployee.EmployeeTitle">Manager</option>
<option value="Admin" ng-model="selectedEmployee.EmployeeTitle">Admin</option>
<option value="OfficeBitch" ng-model="selectedEmployee.EmployeeTitle">Office Bitch</option>
</select>
</div>
<div class="inline-fields">
<label style="margin-left:1px">Last Name:</label>
<input style="width:150px" ng-model="selectedEmployee.EmployeeLastName" type="text">
<label style="margin-left:66px">PM:</label>
<select style="width:150px" ng-model="selectedEmployee.EmployeeIsPM" ng-options="o.v as o.n for o in [{ n: 'No', v: false }, { n: 'Yes', v: true }]">
<option value="true">True</option>
<option value="false">False</option>
</select>
</div>
<div class="inline-fields">
<label style="margin-left:0px">Cell Phone:</label>
<input style="width:150px" ng-model="selectedEmployee.EmployeeCellPhone" type="text" ui-mask="{{'(999) 999-9999'}}">
<label style="margin-left:46px">Super:</label>
<select style="width:150px" ng-model="selectedEmployee.EmployeeIsSuper" ng-options="o.v as o.n for o in [{ n: 'No', v: false }, { n: 'Yes', v: true }]">
<option value="true">True</option>
<option value="false">False</option>
</select>
</div>
<div class="inline-fields">
<label style="margin-left:-14px">Office Phone:</label>
<input style="width:150px" ng-model="selectedEmployee.EmployeeOfficePhone" type="text" ui-mask="{{'(999) 999-9999'}}">
</div>
</div>
</tab>
</tabset>
<!--End Tab Content-->
<br />
<div class="col-xs-12" style="margin-top: 220px;position:absolute">
<input style="margin-left: 3px; width: 70px" ng-click="updateEmployee(selectedEmployee)" type="button" value="Update" go-click="#" />
<input style="margin-left:285px;width:70px" type="submit" value="Save" go-click="#" />
<input style="margin-left: 20px; width: 70px" type="button" ng-if="true" data-dismiss="modal" value="Exit" go-click="#" />
</div>
Controller
//Sync Employee Table with Input Fields "New Employee Modal
$scope.setSelectedEmployee = function (employee) {
$scope.selectedEmployee = employee;
}
//Activate tab on selection
$scope.data = { static: false }
//GET Employees
EmployeeGet.query().then(function (data) {
$scope.employeeArray = data;
}, function (reason) {
errorMngrSvc.handleError(reason);
});
//Clear Employee Search Input Fields
$scope.ClearEmployeeModalFields = function () {
$scope.selectedEmployee.EmployeeCompanyId = '';
$scope.selectedEmployee.EmployeeFirstName = '';
$scope.selectedEmployee.EmployeeLastName = '';
$scope.selectedEmployee.EmployeeTitle = '';
$scope.selectedEmployee.EmployeeCellPhone = '';
$scope.selectedEmployee.EmployeeOfficePhone = '';
$scope.selectedEmployee.EmployeeEmail = '';
$scope.selectedEmployee.CompanyEmployeeId = '';
$scope.selectedEmployee.EmployeeIsSuper = '';
$scope.selectedEmployee.EmployeeIsPM = '';
};
I think the problem is when you are trying to do the object assignment. In Javascript, primitive types are copied by value and reference types are copied by reference.
$scope.setSelectedEmployee = function (employee) {
$scope.selectedEmployee = employee;
};
So when you deleting the $scope.selectedEmployee using $scope.ClearEmployeeModalFields function, it will delete the object in the array of $scope.employeeArray since it shares the same reference.
Try to replace your function with this to copy instead of pointing to same data:
$scope.setSelectedEmployee = function (employee) {
angular.extend($scope.selectedEmployee, employee);
};

Multiple controllers in a meanjs form, submitting empty values

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

AngularJS select not updating after json push

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.

Resources