close bootstrap modal window using angularjs after submit - angularjs

I'm creating an inventory app, and the user has the option to add a new product or edit an existing one. Both options bring up the same modal window, and I want it to close automatically after the user clicks on submit.
Below is part of my code, my entire code is here: http://codepen.io/andresq820/pen/LWGKXW
HTML
<div class="modal fade" id="editItemModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">{{title(item.code)}}</h4>
</div>
<div class="modal-body">
<form name="myEditForm" ng-submit="editProduct(item)">
<div class="form-group">
<label for="code">Code:</label>
<input type="text" size="5" maxlength="5" minlength="3" class="form-control" name="code" id="code"
ng-model="item.code" ng-disabled="false" ng-pattern="/^[a-zA-Z0-9]*$/">
<span ng-show="myEditForm.code.$error.pattern">Code can only be alphanumeric.</span> </br>
<span ng-show="myEditForm.code.$error.minlength">Code has to be at least 3 characters</span>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" name="description" id="description" ng-model="item.description" required>
<span ng-show="myEditForm.description.$touched && myEditForm.description.$invalid">The description is required.</span>
</div>
<div class="form-group">
<label for="amount">Amount:</label>
<input type="number" class="form-control" name="amount" id="amount" size="5" maxlength="5"
ng-model="item.amount" ng-pattern="/^[0-9]{1,7}$/">
<span ng-show="myEditForm.amount.$error.pattern">Only whole numbers are allowed</span>
</div>
<div class="form-group">
<label for="newImage">{{loadImg}}</label>
<input type="file" class="form-control" name="newImage" id="newImage" ng-model="item.image">
</div>
<div class="form-group" ng-show="displayRadioBtns">
<label for="radio">Type:</label>
<div class="radio">
<label><input type="radio" name="optradio" ng-model="item.type" value="in">In</label>
<label><input type="radio" name="optradio" ng-model="item.type" value="out">Out</label>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Close" />
<input type="submit" class="btn btn-primary pull-right" value="Submit" ng-disabled="myEditForm.$invalid"/>
</div>
</form>
</div>
</div>
</div>
</div>
ANGULARJS
$scope.editProduct = function(item){
var index = $scope.items.indexOf(item);
console.log(index);
console.log(item);
console.log(item.code.valueOf());
if(index == -1){
console.log('new item');
$scope.item.code = item.code;
$scope.item.description = item.description;
$scope.item.in = item.amount;
$scope.item.out = 0;
$scope.item.createdOn = Date.now();
$scope.items.push($scope.item);
$scope.item = {};
}else{
console.log('edit item');
console.log(item);
console.log(item.type);
console.log($scope.item.type);
console.log(index);
$scope.items[index].code = item.code;
console.log($scope.items[index].code);
$scope.items[index].description = item.description;
console.log($scope.items[index].description);
$scope.items[index].image = item.image;
if($scope.item.type == 'in'){
console.log($scope.item.type);
console.log(typeof($scope.items[index].in));
console.log(typeof($scope.item.amount));
console.log(typeof(item.amount));
$scope.items[index].in += item.amount;
console.log($scope.items[index].in);
$scope.item = {};
}else if($scope.item.type == 'out'){
console.log($scope.item.type);
$scope.items[index].out += $scope.item.amount;
$scope.item = {};
}else{
alert("Type is a required field");
return;
};
}
};

You can make function calls on ngSubmit
form class="well" (ngSubmit)="addUserModal.hide(); addUser(model); userForm.reset()" #userForm="ngForm"

I haven't used AngularJS, but the following works for me in Angular 2, if you're able to use jQuery:
$(".modal").modal("hide")

Fire button click on submit event in angularJS.
<input id="quemodalcancel" type="submit" value="Cancel" class="btn blue_btn" data-dismiss="modal" aria-hidden="true">
$scope.editProduct = function(item){
// submit button code
document.querySelector('#quemodalcancel').click();
}

Related

AngularJS validations in .NET CSHTML files

My angularjs validation in .NET MVC cshtml files isnt working.
Below is my code:
cshtml code:
<div id="addEditItem" class="modal" role="dialog">
<form novalidate role="form" name="frmItem">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Item Details</h4>
</div>
<div class="modal-body">
<input type="hidden" class="form-control" ng-model="id">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" ng-model="name" maxlength="50" ng-required="true">
<span style="color:red" class="help-block" ng-if="frmItem.name.$error.required && frmItem.name.$dirty">*</span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<button type="submit" class="btn btn-success" ng-click="SaveItem()"><i class="fa fa-save"></i> Submit</button>
</div>
</div>
</div>
</form>
</div>
Controller Code:
medApp.controller("itemController", function ($scope, itemService) {
$scope.SaveItem = function () {
var itemModel = {
Id: $scope.id,
Name: $scope.name,
Description: $scope.description,
Manufacturer: $scope.manufacturer,
BatchNo: $scope.batchNo,
ExpiryDate: $scope.expiryDate
};
if (!CheckIsValid()) {
alert('Please fill the detail!');
return false;
}
var requestResponse = itemService.AddEdit(itemModel);
Message(requestResponse);
};
function CheckIsValid() {
var isValid = true;
if ($('#name').val() === '' || $('#description').val() === '' || $('#manufacturer').val() === '' || $('#batchNo').val() === '') {
isValid = false;
}
return isValid;
}
});
The addEditItem is a modal dialog. If I click on submit the alert('Error in getting records'); is shown.
I want the validation to happen at cshtml level rather than the java alert.
I am going to remove the CheckIsValid function. I want the validation to happen only in cshtml file.
Any idea what's going on?
In your attached cshtml code I could find the "name" id only, but your check function is also checking"description", "manufacturer" and "batchNo". All of those item must be exist otherwise the function returns with false.
The CheckIsValid() function will return true when all items exists and contains at least one character. Anyway the good start is to put a breakpoint into your check code and see why returns with false.
Wordking fiddle
<form name="myForm">
<input type="hidden" class="form-control" ng-model="id">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" ng-model="name" maxlength="50" ng-required="true">
<span style="color:red" class="help-block" ng-show="myForm.name.$error.required && !myForm.name.$valid">*</span>
</div>
<button ng-click="display()">Log</button>
</form>
Would like to add that you need to add:
Use name on inputs to be accesable from the scope
Use ng-show/ng-hide for validation since it changes alot

ng-model is not updating the right user in AngularJS

I am kind of new in AngularJS, and I have a form that users can edit there form. But when user clicks update, it updates the form. BUT, the user does not update the user. Shown in the image
Image here
Here is my code:
<div ng-controller="MyCtrl">
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
</div>
</div>
<!-- the form -->
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="myObject.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="myObject.last">
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="update()">Update</button>
</form>
App.js
var app = angular.module("Portal", ['ngRoute']);
app.controller('MyCtrl', function($scope) {
$scope.inactive = true;
$scope.people = {};
$scope.myObject = JSON.parse(localStorage.getItem('myObject')) || {
first : $scope.people.first,
last : $scope.people.last,
};
$scope.update = function(){
$scope.people.first = $scope.myObject.first;
$scope.people.last = $scope.myObject.last;
localStorage.setItem('myObject', JSON.stringify($scope.myObject));
};
$scope.deletePeople = deletePeople;
function deletePeople(id){
var userToDelete;
$scope.people.forEach(function(p, index){
if(p.id == id){
userToDelete = index;
}
});
$scope.people.splice(userToDelete, 1);
console.log($scope.people);
}
});
List of users
<div class="people" ng-repeat="p in people | filter:userSearch" >
<a href="#/people/{{ p.id }}">
<img ng-src="{{p.img}}"/>
<span class="name">{{p.first}} </span>
<span class="name">{{p.last}} </span>
<p class="title">{{p.title}} </p>
<span class="date">{{p.date}} </span>
</a>
</div>
The people view section should be included under <div ng-controller="MyCtrl"> div. So just move that line up so it's the first line of the code.
Your ng-model in the form needs to be people.first and people.last respectively. E.g. <b>First Name:</b>
<input type="text" ng-model="people.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="people.last">
check this
As Swailem95 said you have to move the <div ng-controller="MyCtrl"> top and it looks like below after that.
<div ng-controller="MyCtrl">
<div class="people-view">
<h2 class="name">{{people.first}}</h2>
<h2 class="name">{{people.last}}</h2>
<span class="title">{{people.title}}</span>
<span class="date">{{people.date}} </span>
</div>
<!-- the form -->
<div class="list-view">
<form>
<fieldset ng-disabled="inactive">
<legend>Basic Info</legend>
<b>First Name:</b>
<input type="text" ng-model="myObject.first">
<br>
<b>Last Name:</b>
<input type="text" ng-model="myObject.last">
</fieldset>
<button type="button" class="edit" ng-show="inactive" ng-click="inactive = !inactive">
Edit
</button>
<button type="submit" class="submit" ng-show="!inactive" ng-click="update()">Update</button>
</form>
</div>
</div>

Unable to pass dynamic form inputs to the controller function

I want a form to be created dynamically with three inputs each time a new data item is found. Whenever the end user clicks on a particular checkbox the selected field name, other input values corresponding to the form group have to be submitted to the controller function. I created a JSFiddle for the layout.
<div class="panel panel-primary" ng-controller="citycontroller as ctrl">
<div class="panel-heading">
Available Cities
</div>
<div class="panel-body">
<h4>
{{data}}
</h4>
<div ng-repeat="x in data" class="[ form-group form-inline ]">
<input class="form-control input-md" type="checkbox" id="{{x.name}}" ng-model="name" autocomplete="off" />
<div class="[ btn-group ]">
<label for="{{x.name}}" class="[ btn btn-success ]">
<span class="[ glyphicon glyphicon-ok ]"></span>
<span> </span>
</label> <label for="{{x.name}}" class="[ btn btn-default active ]">
{{x.name}}
</label>
</div>
<input class="form-control input-md" type="text" placeholder="periodicity" id="x.periodicity" autocomplete="off" />
</div>
<button type="button" class="btn btn-info" style="float: right" ng-click="ctrl.addInfo()">Add</button>
</div>
</div>
Controller method is as follows:
var mainApp = angular.module('cityinfo',[]);
mainApp.controller('citycontroller', function($scope,$http,$window,$interval) {
var cities=[{"name":"hyd","periodicity":"5"},{"name":"chn","periodicity":"5"},{"name":"blr","periodicity":"5"}];
$scope.data = cities;
this.addInfo=function() {
console.log('update city information...');
//get list of city names that are selected by the user in the form here and print their values
}
});
Not getting idea about how to retrieve form values in the controller method addInfo(). Can anyone help me in this regard.
You'll need to track which checkboxes are checked using ng-model.
One approach could be as follows.
HTML:
<div ng-repeat="city in cities">
<input type="checkbox" ng-model="city.checked" />
</div>
JS:
$scope.cities = [{
name: 'foo',
periodicity: 5,
checked: false
}, {
name: 'bar'
periodicity: 6,
checked: false
}]
$scope.addInfo = function() {
// Using lodash
_($scope.cities).filter({checked: true}).each(function(city) {
// do stuff
}
}
You don't have to change your code at all. Just by changing the ng-model of your input you can achieve it:
HTML
</div>
<div class="panel-body">
<h4>
{{data}}
</h4>
<div ng-repeat="x in data" class="[ form-group form-inline ]">
<input class="form-control input-md" type="checkbox" id="{{x.name}}" ng-model="x.value" autocomplete="off" />
<div class="[ btn-group ]">
<label for="{{x.name}}" class="[ btn btn-success ]">
<span class="[ glyphicon glyphicon-ok ]"></span>
<span> </span>
</label>
<label for="{{x.name}}" class="[ btn btn-default active ]">
{{x.name}}
</label>
</div>
<input class="form-control input-md" type="text" placeholder="periodicity" id="x.periodicity" autocomplete="off" />
</div>
<button type="button" class="btn btn-info" style="float: right" ng-click="ctrl.addInfo()">Add</button>
</div>
</div>
SCRIPT
var mainApp = angular.module('myApp',[]);
mainApp.controller('citycontroller', function($scope) {
var cities=[{"name":"hyd","periodicity":"5"},{"name":"chn","periodicity":"5"},{"name":"blr","periodicity":"5"}];
$scope.data = cities;
this.addInfo=function() {
console.log($scope.data);
//get list of city names that are selected by the user in the form here and print their values
}
});
In your browser console check for value. It will be true if checkbox is selected.

Angular and Bootstrap radio buttons conflict When Editing Form

I am unable to get automatic radio button checked when I edit the User From using following Html and AngularJs Code. When I console {{changeUser}} this returns following data
{"id":1,"username":"Ramesh","password":"Ramesh1#23","role":"admin","active":"no"}. When I load the edit form I have to automatically checked the no radio button in the following code.
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form class="form-horizontal form-bordered" name="editUserForm" data-ng-submit="userEdit(changeUser)">
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Username*</label>
<div class="col-md-4">
<input class="form-control" type="text" name="userName" data-ng-model="changeUser.username" value="{{ changeUser.username }}" data-ng-pattern="/^[a-z0-9_ .-]{5,15}$/i" required />
<span style="color:red" class="error" data-ng-show="editUserForm.userName.$error.pattern" >Only letters, integers, and underscores.Minimum 5 characters to maximum 15 characters.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Password*</label>
<div class="col-md-4">
<input class="form-control" type="password" name="changePassword" data-ng-model="changeUser.password" value="{{ changeUser.password}}" data-ng-pattern="usersPattern.password" required />
<span style="color:red" class="error" data-ng-show="editUserForm.changePassword.$error.pattern">Minimum of 8 characters, 1 capital letter,1 lowercase, 1 special-case and 1 numeric.</span>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Action</label>
<div class="col-md-4">
<div class="radio-list">
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changeUser.active" value="yes"/>
Yes
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadios2" data-ng-model="changerUser.active" value="no"/>
No
</label>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn purple" data-ng-disabled= "editUserForm.$invalid">
<i class="fa fa-check"></i> Edit</button>
<button type="button" class="btn red" data-ng-click="cancelEdit()">Cancel</button>
</div>
</div>
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div>
The Controller is
(function (){
"use strict";
function UsersEditController($scope, UserFactory, $http, $location) {
$scope.$on('$viewContentLoaded', function () {
App.initAjax(); // initialize core components
});
$scope.changeUser = {};
$scope.changeUser = UserFactory.get();
$scope.userEdit = function(data) {
$scope.changeUser = data;
console.log($scope.changeUser);
};
$scope.usersPattern = {
password: '((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!##$%]).{8,20})'
};
$scope.cancelEdit = function() {
$location.path('users');
};
}
UsersEditController.$inject = ['$scope', 'UserFactory', '$http', '$location'];
angular.module('books').controller('UsersEditController', UsersEditController);
})()
And I guess this is your answer (even without js code provided :) )
https://stackoverflow.com/a/18446612/552194
You need to add ng-value and use it instead of the standard value

Splice item out of ng-repeat array, when that item is clicked

I have an array of items that I'm repeating.
<li ng-repeat="lineItem in lineItems" class="bouncy-slide-left">
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label for="expenses">{{lineItem.labels.name}}Expense:</label>
<br>
<select name="expenses" ng-model="expense.name" class="form-control" style="width: 175px;">
<option value="{{expense.name}}" ng-repeat="expense in expenses">{{expense.name}}</option>
</select>
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Material Cost:</label>
<br>
<input type="text" ng-model="expense.cost" class="form-control" name="material" placeholder="5.00">
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Quantity:</label>
<br>
<input type="text" ng-model="expense.quantity" class="form-control" name="quantity" placeholder="5">
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Labor Rate:</label>
<br>
<input type="text" ng-model="expense.labor" class="form-control" name="labor" placeholder="20.00">
</div>
<div class="form-group col-sm-5 col-lg-2 col-xl-2 pad-right">
<label>Hours:</label>
<br>
<input type="text" ng-model="expense.hours" class="form-control" name="hours" placeholder="4">
</div>
<div class="form-group col-sm-5 col-lg-3 col-xl-2 pad-right">
<label>Responsible:</label>
<br>
<span>Renter</span>
<input type="radio" name="radio-1">
<span>Owner</span>
<input type="radio" name="radio-1">
</div>
<br>
<div class="col-sm-12 pad-right">
<span class="pad-right">Owner Total: {{ownerTotal}}</span>
<span class="pad-right">Renter Total: {{renterTotal}}</span>
</div>
<div class="col-sm-12 pad-right">
<button class="btn btn-primary btn-sm" ng-click="addExpense()"><i class="fa-check"></i>Add New Expense</button>
<button class="btn btn-primary btn-sm" ng-click="removeExpense($event)"><i class="fa-remove"></i>Remove Expense</button>
</div>
</li>
I have an array, an add method, and a remove method.
$scope.lineItems = [
{expense: 1}
];
//when button is clicked
//add a new blank object to the lineItems array
$scope.addExpense = function() {
var num = Math.random();
var item = {expense: num};
$scope.lineItems.push(item);
};
//when remove button is clicked
//remove the specific item that was clicked from the array
$scope.removeExpense = function($event) {
var elm = $event.currentTarget.parentElement.parentElement;
console.log(elm);
elm.remove();
//need to splice selected item OUT of the array
var i = ???
$scope.lineItems.splice(i, 1);
};
I've tried several things here. Most of the answers I've found just use indexOf, however the items are being dynamically generated by my model. So I don't know how to get an index of something that doesn't exist yet.
I've also tried some jQueryLite. I would love to just use something like : when $this is clicked, remove it from the dom. I can't seem to find the ANGULAR answer for that.
Instead of ng-click="removeExpense($event)" simply pass the lineItem, like ng-click="removeExpense(lineItem)". You can then find the lineItem in lineItems by indexOf
$scope.removeExpense = function(lineItem) {
var index = $scope.lineItems.indexOf(lineItem);
$scope.lineItems.splice(index, 1);
}
call removeExpense($index) on ng-click like:
<button class="btn btn-primary btn-sm" ng-click="removeExpense($index)"><i class="fa-remove"></i>Remove Expense</button>
and replace remove function with this code:
$scope.removeExpense = function(index) {
$scope.lineItems.splice(index, 1);
}

Resources