Append Data to existing json array through Angular-Bootstrap dialog modal - angularjs

I am facing issue while adding data through Angular Dialog modal
Here My plunker
http://plnkr.co/edit/EJpkmXqNAcuN3GJiLvAL?p=preview
<table class="table table-bordered">
<thead>
<tr>
<th>
<input type="checkbox" ng-model="isAll" ng-click="selectAllRows()"/>ALL
</th>
<th>
ID
</th>
<th>
NAME
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data" ng-class="{'success' : tableSelection[$index]}">
<td>
<input type="checkbox" ng-model="tableSelection[$index]" />
</td>
<td>{{row.id}}</td>
<td>{{row.name}}</td>
</tr>
</tbody>
</table>
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">Im a modal!</h3>
</div>
<form name = "addFriendForm">
<input ng-model = "user.id"class="form-control" type = "text" placeholder="id" title=" id" />
<input ng-model = "user.name"class="form-control" type = "text" placeholder="name" title=" name" />
</form>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>***strong text***
Here Script.js
While trying get data from dialog modal it was not coming
Can you please any one help me out of this problem
var app = angular.module('myapp', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope,$modal,$log) {
$scope.user = {id: "",name:""}
$scope.data = [{
id: 1,
name: 'Name 8'
}, {
id: 2,
name: 'Name 7'
}];
$scope.tableSelection = {};
$scope.isAll = false;
$scope.selectAllRows = function() {
//check if all selected or not
if ($scope.isAll === false) {
//set all row selected
angular.forEach($scope.data, function(row, index) {
$scope.tableSelection[index] = true;
});
$scope.isAll = true;
} else {
//set all row unselected
angular.forEach($scope.data, function(row, index) {
$scope.tableSelection[index] = false;
});
$scope.isAll = false;
}
};
$scope.removeSelectedRows = function() {
//start from last index because starting from first index cause shifting
//in the array because of array.splice()
for (var i = $scope.data.length - 1; i >= 0; i--) {
if ($scope.tableSelection[i]) {
//delete row from data
$scope.data.splice(i, 1);
//delete rowSelection property
delete $scope.tableSelection[i];
}
}
};
$scope.addNewRow = function() {
//set row selected if is all checked
$scope.tableSelection[$scope.data.length] = $scope.isAll;
$scope.data.push({
id: $scope.data.length,
name: 'Name ' + $scope.data.length
});
};
$scope.open = function () {
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
data: function () {
return $scope.data;
}
}
});
modalInstance.result.then(function (data) {
$scope.user = data;
$scope.data.push($scope.user);
// $scope.data.push({'id':$scope.data.id,'name':$scope.data.name});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
angular.module('myapp').controller('ModalInstanceCtrl', function ($scope, $modalInstance, data) {
$scope.ok = function () {
$modalInstance.close($scope.user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});

You should create $scope.user object in your ModalInstanceCtrl and add $scope.user in your $modalInstance.close like this:
angular.module('myapp').controller('ModalInstanceCtrl', function ($scope,$modalInstance) {
$scope.user = {};
$scope.ok = function () {
$modalInstance.close($scope.user);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
I've checked this in your plunker, so it works

Related

Pass text box value to services in angular

I have two pages-one is to create data and when I click save button text box values will be send to backend method.In another page am displaying those entered datas in table.So am using two controller methods here.
I dont know how to send text box values to backend using angular.I did it using jquery simply but I dont know angular thats why am struggling.
This is my first page to save text box details:
<div class="row ">
<label>Name<span id="required">*</span></label>
<input type="text" ng-model="item.name" class = "col-lg-5 col-md-5 col-sm-5 col-xs-10"/>
</div>
<div class="row ">
<label class="col-lg-2 col-md-2 col-sm-3 col-xs-12 ">Description</label>
<textarea ng-model="item.description"></textarea>
</div>
<div class="row marTop">
<span class="pull-right">
<button class="btn save btn-primary" ng-click="addItem(item)"><i class="fa fa-floppy-o"></i>Save</button>
<button class="btn cancel btn-default" onclick="window.location.href = '/Admin/RoleList'"><i class="fa fa-ban"></i>Cancel</button>
</span>
</div>
Script: In this method only I need to pass name and description values
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http) {
$scope.items = [];
$scope.addItem = function (item) {
$scope.items.push(item);
$scope.item = {};
}
//$scope.item = aaa;
console.log(item)
//$scope.values = {
// name: 'newroleName',
// description: 'roledescription'
//};
$http.post("/Admin/RolesInsert"){
alert("success")
}
})
</script>
This is my second page to get table data( that saved name should be display in this table)
<table class="table table-hover table-bordered" id="mydata" ng-controller="myCtrl">
<thead class="colorBlue">
<tr>
<th>S.No</th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody id="">
<tr ng-repeat="x in roleList | filter:searchText">
<td>{{x.Id}}</td>
<td>{{x.name}}</td>
<td>
<i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="edit{{x.Id}}"></i>
<i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-click="update{{x.Id}}"></i>
<i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="cancel{{x.Id}}"></i>
</td>
</tr>
</tbody>
</table>
script for second table
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http) {
$scope.values = {
};
$http.post("/Admin/getRolesList")
.then(function (response) {
$scope.roleList = response.data;
});
})
</script>
One of the ways of doing this is:
angular.module("intranet_App", [])
.controller('myCtrl', function ($scope, $http, myFactory) {
...
function sendDataToBackend() {
var requestHeaders = {
"Content-Type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: 'your url',
headers: requestHeaders
};
httpRequest.data = $scope.items;
$http(httpRequest).then(function (response) {
//Handle the response from the server
})
}
}
Finally got an answer:
<script>
var app=angular
.module("intranet_App", [])
.controller('myCtrl', ["$scope","$http", function ($scope, $http ,myFactory) {
$scope.items = [];
$scope.addItem = function (item) {
$scope.items.push(item);
//$scope.oRoles = $scope.item
$scope.json = angular.toJson($scope.item);
console.log($scope.json)
}
$scope.myFunc = function (item) {debugger
$scope.addItem(item);
var requestHeaders = {
"Content-Type": 'application/json'
}
var httpRequest = {
method: 'POST',
url: '/Admin/RolesInsert',
headers: requestHeaders
};
httpRequest.data = $scope.json;
$http(httpRequest).then(function (response) {
alert(response)
//$window.location.href = '/Admin/RoleList';
})
}
}])
</script>

Error: [ng:areq] Argument 'ModalController' is not a function, got undefined

I used to have all my code in one big js file, but i separated everything -- including controllers to make it modular as my little app grows (and for learning porpoises). So my ui-bootstrap modal code is in this controller and is called and worked fine. When i split the controllers into separate files i get the error below. How do i fix?
app.js
var personApp = angular.module('PersonApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);
personController.js
personApp.controller('PersonController', function ($scope, $uibModal, PersonService) {
$scope.addPerson = function () {
$scope.modalModel = {
Id: 0,
firstName: '',
lastName: '',
birthDate: ''
};
$scope.$uibModalInstance = $uibModal.open({
templateUrl: '/Modal/AddEditPersonModal',
controller: 'ModalController',
scope: $scope
})
}
personModalController.js
personApp.controller('ModalController', ['$scope', function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);
Index.cshtml
#{
ViewBag.Title = "Home Page";
}
<link href="~/Content/PageSpecific/Index.css" rel="stylesheet" />
<script src="~/Scripts/PersonApp/app.js"></script>
<script src="~/Scripts/PersonApp/filters/personFilter.js"></script>
<script src="~/Scripts/PersonApp/services/personService.js"></script>
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
<script src="~/Scripts/PageSpecific/Index.js"></script>
<div ng-app="PersonApp" class="container">
<div ng-controller="PersonController">
<div class="mb20 mt15">
<input type="text" placeholder="Search Person" ng-model="searchPerson" />
<button type="button" class="btn btn-primary pull-right mb15 mr20" data-toggle="modal" ng-model="addPersonModel" ng-click="addPerson()">Add New</button>
</div>
<table class="table header-fixed">
<thead>
<tr>
<th ng-click="sortData('Id')">
ID <div ng-class="getSortClass('Id')"></div>
</th>
<th ng-click="sortData('firstName')">
First Name <div ng-class="getSortClass('firstName')"></div>
</th>
<th ng-click="sortData('lastName')">
Last Name <div ng-class="getSortClass('lastName')"></div>
</th>
<th ng-click="sortData('birthDate')">
BirthDate <div ng-class="getSortClass('birthDate')"></div>
</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="person in filteredPersons | orderBy: sortColumn:reverseSort | filter : searchPerson">
<td>{{person.Id}}</td>
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
<td>{{person.birthDate | date:"MM/dd/yyyy"}}</td>
<td>
<span class="fa fa-pencil-square-o"></span>
<span class="fa fa-remove"></span>
</td>
</tr>
</tbody>
</table>
<ul uib-pagination total-items="persons.length" ng-model="currentPage" max-size="maxSize" class="pagination-sm" boundary-links="true" rotate="false" items-per-page="numPerPage" num-pages="numPages"></ul>
<pre>Page: {{currentPage}} / {{numPages}}</pre>
</div>
</div>
<style>
</style>
Was a simple mistake on my part. Changed the order of referenced files in the index.cshtml. personController had function trying to call modalcontroller (in personmodalcontroller)
This:
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
Became this:
<script src="~/Scripts/PersonApp/controllers/personModalController.js"></script>
<script src="~/Scripts/PersonApp/controllers/personController.js"></script>
You missed to include,$uibModalInstance
personApp.controller('ModalController', ['$scope' function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);
Re define the ModalController like this. You have not injected the $uibModalInstance dependency in your controller. the $uibModalInstance inside the function parameters are only the alias reference to your dependency. You have to inject the dependency first before aliasing the dependency.
personApp.controller('ModalController', ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) {
$scope.close = function () {
$scope.$uibModalInstance.close();
var modalId = $scope.modalModel.Id;
for (var i = 0; i < $scope.persons.length; i++) {
var person = $scope.persons[i];
if (person.Id === $scope.oldValues.Id) {
$scope.persons[i].firstName = $scope.oldValues.firstName;
$scope.persons[i].lastName = $scope.oldValues.lastName;
$scope.persons[i].birthDate = $scope.oldValues.birthDate;
break;
}
};
};
$scope.save = function () {
$scope.$uibModalInstance.dismiss('cancel');
};
}]);

angular.js ReferenceError: $document is not defined

Hi I am getting at console :
angular.js:10072ReferenceError: $document is not defined
at link (http://localhost:9999/CheckBoxOperation/:173:15)
at N
<table class="table table-bordered" arrow-selector="">
Actually I am trying to do arrow selection like this http://code.ciphertrick.com/2015/03/15/change-row-selection-using-arrows-in-ng-repeat/
I am getting that error because of code which is inside dashed line in my code. I think it is related to script but I didn't get.
This is my code:
AngularJS check box
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController',[ '$scope', '$http', function($scope, $http)
{
$scope.headerText = ' Form';
$scope.selectedColor;
$scope.Levels=[]; //for checkbox name
$scope.Rows=[]; //for rows
$scope.selection=[];
$scope.selectedRow=0;
$http({method: 'GET', url: 'controller/getLevelCheckBox'}).
success(function(data, status, headers, config)
{
angular.forEach(data, function(value, key)
{
$scope.Levels.push(value);
});
})
// toggle selection for a given level by name
$scope.toggleSelection = function toggleSelection(levelName) {
var idx = $scope.selection.indexOf(levelName);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(levelName);
$scope.getAllJobs = function()
{
var response = $http.get('controller/getDataTable/'+levelName);
response.success(function(data, status, headers, config)
{
angular.forEach(data, function(value, key)
{
$scope.Rows.push(value); //json Array valuessss
});
$scope.setClickedRow = function(index){
// window.alert("row clicked "+index);
$scope.selectedRow = index;
}
$scope.$watch('selectedRow', function() {
console.log('Do Some processing'); //runs the block whenever selectedRow is changed.
});
window.alert("sccusee");
});
response.error(function(data, status, headers, config)
{
alert("staus ::"+status);
});
}//getAllJobs()
}//else
};//toggle function
}]);//controller
app.directive('arrowSelector',function(){
return{
restrict:'A',
link:function(scope,elem,attrs,ctrl){
var elemFocus = false;
elem.on('mouseenter',function(){
elemFocus = true;
console.log(true);
});
elem.on('mouseleave',function(){
elemFocus = false;
console.log(false);
});
//--------------------------------------------------------------
$document.bind('keydown',function(e){
console.log("bind");
if(elemFocus){
if(e.keyCode == 38){
console.log(" 38 kjeeeey ::"+scope.selectedRow);
if(scope.selectedRow == 0){
return;
}
scope.selectedRow--;
scope.$apply();
e.preventDefault();
}
if(e.keyCode == 40){
if(scope.selectedRow == scope.Rows.length - 1){ return;
}
scope.selectedRow++;
scope.$apply();
e.preventDefault();
}
}
}); //till this point
}
};
});
</script>
</head>
<body data-ng-controller="FormSubmitController">
<h3>{{headerText}}</h3>
<div class=panel>
<div class="check-box-panel">
<div data-ng-repeat="level in Levels">
<div class="action-checkbox">
<input id="{{level}}" type="checkbox" value="{{level}}" data-ng-checked="selection.indexOf(level) > -1"
data-ng-click="toggleSelection(level)" />
<label for="{{level}}"></label>
{{level}}
</div>
</div>
<input type="submit" value="show all jobs " data-ng-click="get All Jobs()"/>
</div>
<div class="selected-items-panel">
<table class="table table-bordered" arrow-selector>
<thead>
<tr data-ng-repeat="(key,value) in Rows" data-ng-if="$last">
<td data-ng-repeat="(key,v) in value"><input type="button" value={{key}}></td>
</tr>
<tbody>
<tr data-ng-class="{'selected':$index == selectedRow}" data-ng-click="setClickedRow($index)"
data-ng-repeat="(key,value) in Rows">
<td data-ng-repeat="(key,v) in value">{{v}}</td>
</tr>
</tbody>
</table>
<div>
selectedRow = {{selectedRow}}
</div>
<div>
item = {{Rows[selectedRow]}}
</div>
</div>
</div>
</body>
</html>
You can use angular.element(document) to get the jquery equivalent

ng-selected is not working [duplicate]

This question already has answers here:
AngularJS: ng-selected doesn't show selected value [duplicate]
(2 answers)
Closed 4 years ago.
ng-selected is not working
i select the record for the monitors
and modal opens up with the data for that specific record but combo is not selected
but when i inspect the html it ng-selected is true.
here is the code for html
<h1>Product</h1>
<div id="addProductModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="gridSystemModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="hModalh4Prod" >Add Product</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label col-md-3">Product Name</label>
<input class="form-control" type="text" name="txtproductname" id="txtproductname" maxlength="200" ng-model="vm.product.productName" />
</div>
<div class="form-group">
<label class="control-label col-md-3">Category Name</label>
<!--<input class="form-control col-md-9" type="text" name="txtcategoryname" id="txtcategoryname" maxlength="200" ng-model="vm.category.CategoryName" />-->
<select id="cmbcategory" name="cmbcategory" class="form-control" ng-model="vm.product.categoryId">
<option ng-repeat="cat in vm.Category"
ng-selected="{{cat.categoryID == vm.product.categoryId}}"
value="{{cat.categoryID}}">
{{cat.categoryName}}
{{cat.categoryID == vm.product.categoryId}}
</option>
</select>
</div>
<div class="form-group">
<label class="control-label col-md-3">Product Price</label>
<input class="form-control" type="number" name="txtptoductprice" id="txtptoductprice" maxlength="200" ng-model="vm.product.productPrice" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" ng-click="vm.reset()">Close</button>
<button type="button" id="btnSubmitProd" class="btn btn-primary" ng-disabled="!(vm.product.productName && vm.product.productPrice)" ng-click="vm.add()">Add</button>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-md-offset-10">
<span class="fa fa-plus fa-200px"></span> Add New Record
</div>
</div>
<table class="table table-responsive table-hover">
<thead>
<tr>
<th>Product Name</th>
<th>Category Name</th>
<th>Product Price</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="prod in vm.Products">
<td style="vertical-align:middle">{{prod.productName}}</td>
<td style="vertical-align:middle">{{prod.category.categoryName}}</td>
<td style="vertical-align:middle">{{prod.productPrice}}</td>
<td>
<input type="button" class="btn btn-sm btn-primary" ng-click="vm.edit(prod.productID)" value="Edit" />
<input type="button" class="btn btn-sm btn-primary" ng-click="vm.delete(prod.productID)" value="Delete" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
console.log("In document ready");
});
</script>
and here is the controller
(function () {
'use strict';
app.controller('productController', ['$http', '$location', 'authService', 'ngWEBAPISettings', productController]);
///productController.$inject = ['$location'];
function productController($http, $location, authService, ngWEBAPISettings) {
/* jshint validthis:true */
////debugger;
var vm = this;
vm.title = 'Product';
var d = new Date();
//Creating headers for sending the authentication token along with the system.
var authheaders = {};
authheaders.Authorization = 'Bearer ' + authService.getToken();
//For Cache needs to be updated
var config = {
headers: {
'Authorization': authheaders.Authorization
},
cache: false,
};
vm.Products = [];
vm.Category = [];
vm.product = {
categoryId: 0,
productID:0,
productName: "",
productPrice:0,
createdOn: d,
updatedOn:d
};
//For Populating the Category Combo
vm.getCategory = function () {
////debugger;
////For Grid
$http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Categories?unique=" + new Date().getTime(), config)
.then(function (respose) {
////success
////debugger;
angular.copy(respose.data, vm.Category);
////failure;
//var i = 2;
////debugger;
}, function (response) {
//failure
////debugger;
}).finally(function () {
////debugger;
//finally
}
);
}
////For Grid.
vm.getProducts = function () {
////debugger;
////For Grid
$http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Products?unique=" + new Date().getTime(), config)
.then(function (respose) {
////success
////debugger;
angular.copy(respose.data, vm.Products);
////failure;
//var i = 2;
////debugger;
}, function (response) {
//failure
////debugger;
}).finally(function () {
////debugger;
//finally
}
);
}
//// For adding the new record.
vm.add = function () {
////authheaders.Content-Type="application/x-www-form-urlencoded";
////debugger;
////alert('in add');
vm.product.createdOn = d;
vm.product.updatedOn = d;
$http.post(ngWEBAPISettings.apiServiceBaseUri + "api/Products", JSON.stringify(vm.product), { headers: authheaders })
.then(function (repose) {
////success
////debugger;
vm.Products.push(repose.data);
alert('Category has been addded successfully');
$('#addProductModal').modal('hide');
}, function (response) {
////failure
////debugger;
alert('An error has been occurred while adding the data');
}).finally(function () {
vm.category = {};
});
}
////For showing the edit modal and do events setting to call update instead of add.
vm.edit = function (id) {
///debugger;
////var id = vm.category.categoryID;
////vm.category = {};
$http.get(ngWEBAPISettings.apiServiceBaseUri + "api/Products/" + id, config)
.then(function (response) {
//success
debugger;
//show modal
$('#btnSubmitProd').html('Update');
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.editFinal);
$('#hModalh4Prod').html('Edit Product');
$('#addProductModal').modal('show');
vm.product = response.data;
////vm.getCategory();
//vm.category.CategoryID = response.data.categoryID;
//vm.category.CategoryName = response.data.categoryName;
//vm.category.CreatedOn = response.data.createdOn;
//vm.category.UpdatedOn = response.data.updatedOn;
////categoryID = response.data.categoryID;
//vm.category = {};
}, function (response) {
//failure
debugger;
alert('Unable to fetch the data for desired id.');
}).finally(function () {
})
}
////For doing the final update of edited record and save it into the db.
vm.editFinal = function () {
////debugger;
//// alert('in update final' + categoryID);
//goes in finally
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.add);
$http.put(ngWEBAPISettings.apiServiceBaseUri + "api/Products/" + vm.category.CategoryID, JSON.stringify(vm.category), { headers: authheaders })
.then(function (response) {
//success
////debugger;
updateProduct(vm.category.CategoryID, vm.category);
alert('Record has been updated successfully');
$('#addProductModal').modal('hide');
}, function (response) {
//failure
/////debugger;
alert('There has been error while updating the record');
}).finally(function () {
//final
////debugger;
vm.category = {};
})
}
vm.delete = function (id) {
////debugger;
///alert(id);
if (confirm('Are you sure you want to save this thing into the database?')) {
$http.delete(ngWEBAPISettings.apiServiceBaseUri + "api/Products/" + id, { headers: authheaders })
.then(function (reponse) {
////debugger;
deleteProduct(id);
alert('Record has been delete successfully');
}, function (response) {
/////debugger;
alert('There is some problem in delete record');
}
).finally(function () { })
}
else {
// Do nothing!
}
}
////For resetting Product object after close of modal.
vm.reset = function () {
vm.category = {};
}
activate();
function activate() {
vm.getProducts();
vm.getCategory();
////This event is fired immediately when the hide instance method has been called.
///called to reset the events and the headers.
$('#addProductModal').on('hidden.bs.modal', function () {
////debugger;
vm.category = {};
$('#btnSubmitProd').html('Add');
$('#hModalh4Prod').html('Add Category');
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.add);
console.log("modal is closed hidden");
})
////This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).
///called to reset the events and the headers.
$('#addProductModal').on('hide.bs.modal', function () {
////debugger;
vm.category = {};
$('#btnSubmitProd').html('Add');
$('#hModalh4Prod').html('Add Category');
angular.element($("#btnSubmitProd")).off('click');
angular.element($("#btnSubmitProd")).on('click', vm.add);
console.log("modal is closed hide");
})
}
////update the product object in grid after update.
function updateCategory(value, product) {
for (var i in vm.Products) {
if (vm.Products[i].productID == value) {
//var cat = {};
//cat.categoryID = category.CategoryID;
//cat.categoryName = category.CategoryName;
//cat.createdOn = category.CreatedOn;
//cat.updatedOn = category.UpdatedOn;
vm.Category[i] = product;
break; //Stop this loop, we found it!
}
}
}
function deleteProduct(value) {
for (var i in vm.Products) {
if (vm.Products[i].productID == value) {
delete vm.Products.splice(i, 1);
break; //Stop this loop, we found it!
}
}
}
vm.openAddProductModal = function ()
{
vm.product = {};
$('#addProductModal').modal('show');
$('#btnSubmitProd').html('Add');
$('#hModalh4Prod').html('Add Product');
}
}
})();
it works after changing using ng-option by doing this
<select class="form-control col-md-9" ng-options="cat as cat.categoryName for cat in vm.Category track by cat.categoryID" ng-model="vm.product.category"></select>

Input fields values is not passing to controller

I have been stuck on this for a while. I have a Job class that has multiple ChangeOrders and Purchase Orders. I can create a New Job without problems. I use the same code to Post the New CO and PO. The problem is the values are not binding to there controllers. The difference between the New Job and CO/PO is I am using $rootScope and ngStorage to insert the JobId into the CO/PO modals.
Purchase Order Modal
//New PurchaseOrder Modal
$scope.NewPurchaseOrderModal = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modals/NewPurchaseOrderModal.html',
controller: 'NewPurchaseOrderModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
p: function () {
return $scope.p;
}
}
});
};
Purchase Order POST
//Post New Purchase Orders
$scope.submitPO = function () {;
$scope.job = {};
alert($scope.PONumber);
var data = {
JobId: $scope.job.JobId,
PONumber: $scope.PONumber,
PODate: $scope.PODate,
POAmount: $scope.POAmount,
POLastPrintDate: $scope.POLastPrintDate,
POEmail: $scope.POEmail,
POPrint: $scope.POPrint,
POFaxNumber: $scope.POFaxNumber,
PONotes: $scope.PONotes,
POCreatedBy: $scope.POCreatedBy,
PODeliveryDate: $scope.PODeliveryDate,
POShipVia: $scope.POShipVia,
POShowPrices: $scope.POShowPrices,
POCostCode: $scope.POCostCode,
POApprovedNumber: $scope.POApprovedNumber,
POBackorder: $scope.POBackorder,
}
$http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', data).success(function (data, status, headers) {
console.log(data);
$scope.cancelNewPurchaseOrderModal();
});
};
});
Purchase Order View
<div class="container" style="margin-top:20px" ng-controller="POCtrl">
<form ng-submit="submitPO()" enctype="multipart/form-data">
<fieldset>
<tabset>
<tab heading="Cover">
<div class="col-xs-12" style="margin-top:10px">
<div class="inline-fields" style="" ng-show="true">
<label>JobId:</label>
<input style="width:150px;" ng-model="job.JobId" type="text" />
</div>
<div class="inline-fields">
<label></label>
<input style="width:150px;margin-left:81px" ng-model="job.JobName" type="text" />
<label style="margin-left:268px">Number:</label>
<input style="width:150px" ng-model="PONumber" type="text" />
</div>
<div class="inline-fields">
<label style="margin-left:48px">Attn:</label>
<input style="width:150px;" ng-model="ChangeOrderAttn" type="text" />
<label style="margin-left:291px">Date:</label>
<input style="width:150px" ng-model="PODate" type="date" />
</div>
<div class="inline-fields">
<label style="margin-left:39px">Email:</label>
<input style="width: 150px;" ng-model="POEmail" type="text" />
<label style="margin-left:217px">GC Ref Number:</label>
<input style="width:150px" ng-model="POApprovedNumber" type="text" />
</div>
<div class="inline-fields">
<label style="margin-left:52px">Fax:</label>
<input style="width: 150px; " ng-model="POFaxNumber" type="text" />
<label style="margin-left:233px">Delivery Date:</label>
<input style="width:150px" ng-model="PODeliveryDate" type="date" />
</div>
<div class="inline-fields">
<label style="margin-left: 438px">Approved Amount:</label>
<input style="width:150px" ng-model="ChangeOrderApprovedAmount" type="text" />
</div>
</div><!--End col-xs-6-->
<div class="col-xs-12">
<div class="inline-fields" style="margin-top:30px;margin-left:2px">
<label>Created By:</label>
<input style="width:635px" ng-model="POCreatedBy" type="text" />
</div>
<div class="inline-fields" style="margin-left:37px">
<label>Notes:</label>
<textarea style="width:635px;height:200px" ng-model="PONotes"></textarea>
</div>
<div class="inline-fields" style="margin-top:10px;margin-left:509px">
<label>Amount:</label>
<input style="width:150px" ng-model="POAmount" type="text" />
</div>
</div>
<div class="col-xs-12" style="margin-top:30px;padding-bottom:20px">
<input style="margin-left:435px;width:75px;margin-right:25px" ng-click="printEditChangeOrderModal()" type="button" value="Print" go-click="#" />
<input style="margin-right:25px;width:75px" type="submit" value="Save" go-click="#" />
<input style="width:75px" type="button" ng-click="cancelNewPurchaseOrderModal();" value="Exit" go-click="#" />
</div><!--End col-xs-12-->
</tab><!--End Cover Content-->
<tab heading="Details">...</tab>
<tab heading="Items">...</tab>
</tabset><!--End Tab Content-->
</fieldset><!--End Fieldset-->
</form>
Function to set the JobId in sessionStorage
//Sync Table Selections / sessionStorage
$scope.selectedJob = $sessionStorage.$default($scope.jobArray[1]);
$scope.selectJob = function (job) {
$rootScope.job = job;
angular.extend($scope.selectedJob, job);
console.log($rootScope.job);
};
$scope.clearSelectedJob = function () {
$sessionStorage.$reset();
};
table to select which Job is set in Storage
<div id="scrollArea" style="margin-top:40px" ng-controller="JobCtrl">
<table class=" table table-striped table-hover">
<thead> <tr><th>No</th><th>Name</th></tr></thead>
<tbody>
<tr ng-repeat="job in jobArray" class="pointer no_selection" ng-class="{highlight: job.JobNumber===selectedJob.JobNumber}">
<td ng-dblclick="EditJobModal(job.JobId)" ng-click="selectJob(job)">{{job.JobNumber}}</td>
<td ng-dblclick="EditJobModal(job.JobId)" ng-click="selectJob(job)">{{job.JobName}}</td>
</tr>
</tbody>
</table>
</div><!--End Job Table-->
PO Controller
'use strict';
app.controller('POCtrl', function ($scope, $rootScope, $resource, $http, $filter,
$q, $modal, PO, POGet, POFactory, notificationFactory) {
//New PurchaseOrder Modal
$scope.NewPurchaseOrderModal = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modals/NewPurchaseOrderModal.html',
controller: 'NewPurchaseOrderModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
p: function () {
return $scope.p;
}
}
});
};
//Edit PurchaseOrder Modal
$scope.EditPurchaseOrderModal = function (id) {
$.get('/api/apiPurchaseOrder/' + id, function (data) {
$scope.items = data;
var modalInstance = $modal.open({
templateUrl: 'views/modals/EditPurchaseOrderModal.html',
controller: 'EditPurchaseOrderModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
items: function () {
return $scope.items;
}
}
});
});
};
//GET PurchaseOrders
POGet.query().then(function (data) {
$scope.poArray = data;
}, function (reason) {
errorMngrSvc.handleError(reason);
});
//Post New Purchase Orders
$scope.submitPO = function () {;
$http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', $scope.data).success(function (data, status, headers) {
$scope.cancelNewPurchaseOrderModal();
});
};
//$scope.submitPO = function () {;
// $scope.job = {};
// alert($scope.PONumber);
// var data = {
// JobId: $scope.job.JobId,
// PONumber: $scope.PONumber,
// PODate: $scope.PODate,
// POAmount: $scope.POAmount,
// POLastPrintDate: $scope.POLastPrintDate,
// POEmail: $scope.POEmail,
// POPrint: $scope.POPrint,
// POFaxNumber: $scope.POFaxNumber,
// PONotes: $scope.PONotes,
// POCreatedBy: $scope.POCreatedBy,
// PODeliveryDate: $scope.PODeliveryDate,
// POShipVia: $scope.POShipVia,
// POShowPrices: $scope.POShowPrices,
// POCostCode: $scope.POCostCode,
// POApprovedNumber: $scope.POApprovedNumber,
// POBackorder: $scope.POBackorder,
// }
// $http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', data).success(function (data, status, headers) {
// console.log(data);
// $scope.cancelNewPurchaseOrderModal();
// });
//};
});//End POCtrl
app.controller('NewPurchaseOrderModalInstanceCtrl', function ($scope, $modalInstance) {
$scope.cancelNewPurchaseOrderModal = function () {
$modalInstance.dismiss('cancel');
};
});
app.controller('EditPurchaseOrderModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.cancelEditPurchaseOrderModal = function () {
$modalInstance.dismiss('cancel');
};
});
Job Controller
'use strict';
app.controller('JobCtrl', function ($scope, $rootScope, $resource, $route, $http, $filter,
$q, $modal, $sessionStorage, Job, JobGet, jobFactory, notificationFactory) {
//New Job Modal
$scope.NewJobModal = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modals/NewJobModal.html',
controller: 'NewJobModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
p: function () {
return $scope.p;
}
}
});
};
$scope.EditJobModal = function (id) {
$.get('/api/apiJob/' + id, function (data) {
$scope.items = data;
var modalInstance = $modal.open({
templateUrl: 'views/modals/EditJobModal.html',
controller: 'EditJobModalInstanceCtrl',
windowClass: 'large-Modal',
resolve: {
items: function () {
return $scope.items;
}
}
});
});
};
//GET Jobs
$scope.jobArray = {};
JobGet.query().then(function (data) {
$scope.jobArray = data;
}, function (reason) {
errorMngrSvc.handleError(reason);
});
//Post New Job
$scope.submitJob = function () {
var data = {
GeoAreaId: $scope.newItems.GeoAreaId,
JobTypeId: $scope.newItems.JobTypeId,
JobClassId: $scope.newItems.JobClassId,
CustomerId: $scope.newItems.CustomerId,
JobId: $scope.newItems.JobId,
JobNumber: $scope.newItems.JobNumber,
JobName: $scope.newItems.JobName,
JobDescription: $scope.newItems.JobDescription,
JobOriginalContract: $scope.newItems.JobOriginalContract,
JobBillingDate: $scope.newItems.JobBillingDate,
JobTotalCO: $scope.newItems.JobTotalCO,
JobRevisedContract: $scope.newItems.JobRevisedContract,
}
$http.post('/api/apiJob/PostNewJob', data).success(function (data, status, headers) {
console.log(data);
$scope.cancelNewJobModal();
$scope.$evalAsync(function () {
$scope.data;
});
});
};
//Update Job
$scope.updateJob = function (job) {
jobFactory.updateJob(job).success(successCallback)
.error(errorCallback);
console.log(job);
$scope.cancelEditJobModal();
$scope.$evalAsync(function () {
$scope.job;
});
};
var successCallback = function (job, status, headers, config) {
notificationFactory.success();
};
var errorCallback = function (job, status, headers, config) {
notificationFactory.error(job.ExceptionMessage);
};
//Sync Table Selections / sessionStorage
$scope.selectedJob = $sessionStorage.$default($scope.jobArray[1]);
$scope.selectJob = function (job) {
$rootScope.job = job;
angular.extend($scope.selectedJob, job);
console.log($rootScope.job);
};
$scope.clearSelectedJob = function () {
$sessionStorage.$reset();
};
$scope.newItems = {};
//Typeahead New Job Customer select
$scope.selectNewCustomer = function (customer) {
$scope.newItems.CustomerId = customer.CustomerId;
$scope.newItems.Customer.CustomerName = customer.CustomerName;
$scope.newItems.Customer.CustomerAddress = customer.CustomerAddress;
$scope.newItems.Customer.CustomerCity = customer.CustomerCity;
$scope.newItems.Customer.CustomerState = customer.CustomerState;
$scope.newItems.Customer.CustomerZipcode = customer.CustomerZipcode;
$scope.newItems.Customer.CustomerPhoneNumber = customer.CustomerPhoneNumber;
$scope.newItems.Customer.CustomerFaxNumber = customer.CustomerFaxNumber;
$scope.newItems.Customer.CustomerWebsite = customer.CustomerWebsite;
$scope.newItems.Customer.CustomerOtherShit = customer.CustomerOtherShit;
$scope.newItems.Customer.CustomerHidden = customer.CustomerHidden;
$scope.newItems.Customer.CustomerPM = customer.CustomerPM;
$scope.newItems.Customer.CustomerAdmin = customer.CustomerAdmin;
$scope.newItems.Customer.CustomerAccountant = customer.CustomerAccountant;
};
});//End Job Controller
app.controller('NewJobModalInstanceCtrl', function ($scope, $modalInstance) {
$scope.cancelNewJobModal = function () {
$modalInstance.dismiss('cancel');
};
});
app.controller('EditJobModalInstanceCtrl', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.cancelEditJobModal = function () {
$modalInstance.dismiss('cancel');
};
});
I'd change to be handled everything in a single model which is easier to:
$scope.submitPO = function () {
$scope.data.jobId = $rootscope.job.id; //make sense?
$http.post('/api/apiPurchaseOrder/PostNewPurchaseOrder', $scope.data).success(function (data, status, headers) {
$scope.cancelNewPurchaseOrderModal();
});
};
the view:
<div class="inline-fields" style="" ng-show="true">
<label>JobId:</label>
<input style="width:150px;" ng-model="data.job.JobId" type="text" />
</div>
.....
<div class="inline-fields">
<label style="margin-left:48px">Attn:</label>
<input style="width:150px;" ng-model="data.ChangeOrderAttn" type="text" />
<label style="margin-left:291px">Date:</label>
<input style="width:150px" ng-model="data.PODate" type="date" />
</div>
and remove this $scope.job = {}; from your submit function, it looks like you are 'reseting' the job to an empty object

Resources