ng-selected is not working [duplicate] - angularjs

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>

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>

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

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

Image uploading/cropping functionality is not working in tabset in angularjs

I am new to angularjs.
I want to implement https://angular-file-upload.appspot.com/ image upload functionality in tabs. When I put html elements which are required for image upload inside
<tabset><tab></tab></tabset> it doesn't work, but when I put it outside tabset it worked fine, but I want it inside <tabset><tab></tab></tabset>.
I am getting this error when I put html code inside <tabset></tabset>
Error: document.getElementById(...) is null
handleDynamicEditingOfScriptsAndHtml#http://localhost/angularAdmin/js/controllers/userForm.js:190:34
#http://localhost/angularAdmin/js/controllers/userForm.js:189:1
invoke#http://localhost/angularAdmin/vendor/angular/angular.js:4118:14
$ControllerProvider/this.$get</</<#http://localhost/angularAdmin/vendor/angular/angular.js:8356:11
nodeLinkFn/<#http://localhost/angularAdmin/vendor/angular/angular.js:7608:13
forEach#http://localhost/angularAdmin/vendor/angular/angular.js:347:11
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7607:11
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3768:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6996:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
$ViewDirectiveFill/<.compile/<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3866:9
invokeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:8125:9
nodeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:7637:1
compositeLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6993:13
publicLinkFn#http://localhost/angularAdmin/vendor/angular/angular.js:6872:30
updateView#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3800:23
$ViewDirective/directive.compile/</<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3762:11
$RootScopeProvider/this.$get</Scope.prototype.$broadcast#http://localhost/angularAdmin/vendor/angular/angular.js:14518:15
transitionTo/$state.transition<#http://localhost/angularAdmin/vendor/angular/angular-ui-router/angular-ui-router.js:3169:11
processQueue#http://localhost/angularAdmin/vendor/angular/angular.js:12984:27
scheduleProcessQueue/<#http://localhost/angularAdmin/vendor/angular/angular.js:13000:27
$RootScopeProvider/this.$get</Scope.prototype.$eval#http://localhost/angularAdmin/vendor/angular/angular.js:14200:16
$RootScopeProvider/this.$get</Scope.prototype.$digest#http://localhost/angularAdmin/vendor/angular/angular.js:14016:15
$RootScopeProvider/this.$get</Scope.prototype.$evalAsync/<#http://localhost/angularAdmin/vendor/angular/angular.js:14238:15
completeOutstandingRequest#http://localhost/angularAdmin/vendor/angular/angular.js:4842:7
Browser/self.defer/timeoutId<#http://localhost/angularAdmin/vendor/angular/angular.js:5215:7
<div ui-view="" class="fade-in ng-scope">
[1]: https://angular-file-upload.appspot.com/
app.js
'use strict';
angular.module('app', [
'ngFileUpload',
'toaster',
'LocalStorageModule',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ngStorage',
'ui.router',
'ui.bootstrap',
'ui.load',
'ui.jq',
'ui.validate',
'oc.lazyLoad',
'pascalprecht.translate'
]);
Controller
'use strict';
/* Controllers */
var version = '3.0.6';
// Form controller
app.controller('FormProfileCtrl', ['$scope', '$http', '$timeout', '$compile', '$upload', function ($scope, $http, $timeout, $compile, $upload) {
$scope.usingFlash = FileAPI && FileAPI.upload != null;
$scope.fileReaderSupported = window.FileReader != null && (window.FileAPI == null || FileAPI.html5 != false);
$scope.changeAngularVersion = function () {
window.location.hash = $scope.angularVersion;
window.location.reload(true);
};
$scope.angularVersion = window.location.hash.length > 1 ? (window.location.hash.indexOf('/') === 1 ?
window.location.hash.substring(2) : window.location.hash.substring(1)) : '1.2.20';
$scope.$watch('files', function (files) {
console.log(files);
$scope.formUpload = false;
if (files != null) {
for (var i = 0; i < files.length; i++) {
$scope.errorMsg = null;
(function (file) {
generateThumbAndUpload(file);
})(files[i]);
}
}
});
$scope.uploadPic = function (files) {
$scope.formUpload = true;
if (files != null) {
generateThumbAndUpload(files[0])
}
}
function generateThumbAndUpload(file) {
$scope.errorMsg = null;
$scope.generateThumb(file);
if ($scope.howToSend == 1) {
uploadUsing$upload(file);
} else if ($scope.howToSend == 2) {
uploadUsing$http(file);
} else {
uploadS3(file);
}
}
$scope.generateThumb = function (file) {
if (file != null) {
if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
$timeout(function () {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function (e) {
$timeout(function () {
file.dataUrl = e.target.result;
});
}
});
}
}
}
function uploadUsing$upload(file) {
file.upload = $upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'my-header': 'my-header-value'
},
fields: {username: $scope.username},
file: file,
fileFormDataName: 'myFile',
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
file.upload.xhr(function (xhr) {
// xhr.upload.addEventListener('abort', function(){console.log('abort complete')}, false);
});
}
function uploadUsing$http(file) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
$timeout(function () {
file.upload = $upload.http({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload' + $scope.getReqParams(),
method: 'POST',
headers: {
'Content-Type': file.type
},
data: e.target.result
});
file.upload.then(function (response) {
file.result = response.data;
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}, 5000);
}
fileReader.readAsArrayBuffer(file);
}
function uploadS3(file) {
file.upload = $upload
.upload({
url: $scope.s3url,
method: 'POST',
fields: {
key: file.name,
AWSAccessKeyId: $scope.AWSAccessKeyId,
acl: $scope.acl,
policy: $scope.policy,
signature: $scope.signature,
"Content-Type": file.type === null || file.type === '' ? 'application/octet-stream' : file.type,
filename: file.name
},
file: file,
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
storeS3UploadConfigInLocalStore();
}
$scope.generateSignature = function () {
$http.post('/s3sign?aws-secret-key=' + encodeURIComponent($scope.AWSSecretKey), $scope.jsonPolicy).
success(function (data) {
$scope.policy = data.policy;
$scope.signature = data.signature;
});
}
if (localStorage) {
$scope.s3url = localStorage.getItem("s3url");
$scope.AWSAccessKeyId = localStorage.getItem("AWSAccessKeyId");
$scope.acl = localStorage.getItem("acl");
$scope.success_action_redirect = localStorage.getItem("success_action_redirect");
$scope.policy = localStorage.getItem("policy");
$scope.signature = localStorage.getItem("signature");
}
$scope.success_action_redirect = $scope.success_action_redirect || window.location.protocol + "//" + window.location.host;
$scope.jsonPolicy = $scope.jsonPolicy || '{\n "expiration": "2020-01-01T00:00:00Z",\n "conditions": [\n {"bucket": "angular-file-upload"},\n ["starts-with", "$key", ""],\n {"acl": "private"},\n ["starts-with", "$Content-Type", ""],\n ["starts-with", "$filename", ""],\n ["content-length-range", 0, 524288000]\n ]\n}';
$scope.acl = $scope.acl || 'private';
function storeS3UploadConfigInLocalStore() {
if ($scope.howToSend == 3 && localStorage) {
localStorage.setItem("s3url", $scope.s3url);
localStorage.setItem("AWSAccessKeyId", $scope.AWSAccessKeyId);
localStorage.setItem("acl", $scope.acl);
localStorage.setItem("success_action_redirect", $scope.success_action_redirect);
localStorage.setItem("policy", $scope.policy);
localStorage.setItem("signature", $scope.signature);
}
}
(function handleDynamicEditingOfScriptsAndHtml($scope, $http) {
$scope.defaultHtml = document.getElementById('editArea').innerHTML.replace(/\t\t\t\t/g, '');
$scope.editHtml = (localStorage && localStorage.getItem("editHtml" + version)) || $scope.defaultHtml;
function htmlEdit(update) {
document.getElementById("editArea").innerHTML = $scope.editHtml;
$compile(document.getElementById("editArea"))($scope);
$scope.editHtml && localStorage && localStorage.setItem("editHtml" + version, $scope.editHtml);
if ($scope.editHtml != $scope.htmlEditor.getValue())
$scope.htmlEditor.setValue($scope.editHtml);
}
$scope.$watch("editHtml", htmlEdit);
$scope.htmlEditor = CodeMirror(document.getElementById('htmlEdit'), {
lineNumbers: true, indentUnit: 4,
mode: "htmlmixed"
});
$scope.htmlEditor.on('change', function () {
if ($scope.editHtml != $scope.htmlEditor.getValue()) {
$scope.editHtml = $scope.htmlEditor.getValue();
htmlEdit();
}
});
})($scope, $http);
$scope.confirm = function () {
return confirm('Are you sure? Your local changes will be lost.');
}
$scope.getReqParams = function () {
return $scope.generateErrorOnServer ? "?errorCode=" + $scope.serverErrorCode +
"&errorMessage=" + $scope.serverErrorMsg : "";
}
angular.element(window).bind("dragover", function (e) {
e.preventDefault();
});
angular.element(window).bind("drop", function (e) {
e.preventDefault();
});
}])
;
View
<div class="bg-light lter b-b wrapper-md">
<h1 class="m-n font-thin h3">Edit User</h1>
</div>
<div class="wrapper-md">
<!-- breadcrumb -->
<div>
<ul class="breadcrumb bg-white b-a">
<li><a ui-sref="app.dashboard"><i class="fa fa-home"></i> Dashboard</a></li>
<li class="active">Edit User</li>
</ul>
</div>
<!-- / breadcrumb -->
<div class="col-lg-12">
<div class="wrapper-md" ng-controller="FormProfileCtrl">
<form name="userForm" class="form-validation">
<tabset justified="true" class="tab-container">
<tab heading="Personal Information">
<div class="panel-body">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" ng-model="user.vName" >
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" ng-model="user.vEmail">
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vPhone" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vAddress" ></textarea>
</div>
<div class="form-group pull-in clearfix">
<div class="col-sm-6">
<label>Enter password</label>
<input type="password" class="form-control" name="vPassword" ng-model="vPassword" >
</div>
<div class="col-sm-6">
<label>Confirm password</label>
<input type="password" class="form-control" name="confirm_password" required ng-model="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' ">
<span ng-show='form.confirm_password.$error.validator'>Passwords do not match!</span>
</div>
</div>
</div>
</tab>
<tab heading="Company Information">
<div class="form-group">
<label>Company Name</label>
<input type="text" class="form-control" ng-model="user.vCompanyName" >
</div>
<div class="form-group">
<label>Phone</label>
<input type="text" class="form-control" ng-model="user.vCompanyPhone" >
</div>
<div class="form-group">
<label>Designation</label>
<input type="text" class="form-control" ng-model="user.vDesignation" >
</div>
<div class="form-group">
<label>Address</label>
<textarea class="form-control" ng-model="user.vCompanyAddress" ></textarea>
</div>
</tab>
</tabset>
<!-- I want -->
<div class="upload-div">
<div class="upload-buttons">
<div id="editArea">
<fieldset><legend>Upload right away</legend>
<div ng-file-drop ng-file-select ng-model="files" ng-model-rejected="rejFiles"
drag-over-class="{accept:'dragover', reject:'dragover-err', delay:100}" class="drop-box"
ng-multiple="true" allow-dir="true" ng-accept="'image/*,application/pdf'">
Drop Images or PDFs<div>or click to select</div>
</div>
<div ng-no-file-drop class="drop-box">File Farg&Drop not supported on your browser</div>
</fieldset>
<br/>
</div>
</div>
<ul ng-show="rejFiles.length > 0" class="response">
<li class="sel-file" ng-repeat="f in rejFiles">
Rejected file: {{f.name}} - size: {{f.size}}B - type: {{f.type}}
</li>
</ul>
<ul ng-show="files.length > 0" class="response">
<li class="sel-file" ng-repeat="f in files">
<img ng-show="f.dataUrl" ng-src="{{f.dataUrl}}" class="thumb">
<span class="progress" ng-show="f.progress >= 0">
<div style="width:{{f.progress}}%">{{f.progress}}%</div>
</span>
<button class="button" ng-click="f.upload.abort();
f.upload.aborted = true"
ng-show="f.upload != null && f.progress < 100 && !f.upload.aborted">Abort</button>
{{f.name}} - size: {{f.size}}B - type: {{f.type}}
<a ng-show="f.result" href="javascript:void(0)" ng-click="f.showDetail = !f.showDetail">details</a>
<div ng-show="f.showDetail">
<br/>
<div data-ng-show="f.result.result == null">{{f.result}}</div>
<ul>
<li ng-repeat="item in f.result.result">
<div data-ng-show="item.name">file name: {{item.name}}</div>
<div data-ng-show="item.fieldName">name: {{item.fieldName}}</div>
<div data-ng-show="item.size">size on the serve: {{item.size}}</div>
<div data-ng-show="item.value">value: {{item.value}}</div>
</li>
</ul>
<div data-ng-show="f.result.requestHeaders" class="reqh">request headers: {{f.result.requestHeaders}}</div>
</div>
</li>
</ul>
<br/>
<div class="err" ng-show="errorMsg != null">{{errorMsg}}</div>
</div>
<input type="hidden" class="form-control" ng-model="user.iUserID">
<input type="submit" class="btn btn-success" ng-click="postForm(user)">
</form>
</div>
</div>
I had a similar problem with ng-file-upload and tabset. Here is how I solved it.
In my controller, I created a new object:
$scope.tab_data = {}
and then changed the watch to
$scope.$watch 'tab_data.files', ->
$scope.upload $scope.tab_data.files
Lastly, I updated the ng-model in my html tag.
<div ngf-drop ngf-select ng-model="tab_data.files" class="drop-box" ngf-drag-over-class="dragover" ngf-multiple="true" ngf-allow-dir="true" ngf-accept="'.jpg,.png,.pdf'" class="drop-box">
<div ngf-drop-available >Drop Images here</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>
<div>click to select</div>
</div>
Of course my solution is in coffeescript...sorry if that is an issue but it should be easy for you to convert back to js.

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

ng-click ng-keypress passing form data not working

Im trying to send data from user input to display on the screen when button click.
The problem is that if i click on the button it simply passes to the next value without gathering the information and displaying in the screen. If i press ENTER it works how it should. i have searched all over internet several examples but simply couldnt get it to work. im using at the moment :
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
full html:
<div class="boxContent col-md-12">
<h1>{{lang.sec101.h1}}</h1>
<div class="col-md-12 lineBorder noPad" >
<div class="box1">
<p>
{{lang.sec101.title}}
</p>
</div>
<!-- dynamic form -->
<div class="col-md-12 borderBox boxLeft bg_box">
<form novalidate name="addForm">
<div class="boxLeft" ng-show="Question != ''">
<div ng-show="Question.infotip != 'yes'">
<h1 class="heading_left">{{Question.ask}}</h1>
</div>
<div ng-show="Question.infotip == 'yes'">
<h1 class="heading_left info">{{Question.ask}}
<span class="infotip yourData" tooltip-placement="top" tooltip-trigger="click" tooltip="{{Question.infotipText}}"></span>
</h1>
</div>
</div>
<div class="boxRight" ng-show="Question != ''">
<button class="btn btn-lg btn-default next bt_submits" type="button" ng-click="addData(newData)">
<span class="bt_arrow"></span>
</button>
</div>
<div class="boxRejestracjaInput">
<!-- <div id="legg-select" ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</div> -->
<div class="newSelect">
<label ng-if="Question.type === 'select'">
<select ng-options="opt.val for opt in Question.options" name="{{Question.name}}" ng-model="value" ng-keypress="enter($event,value.val)"></select>
</label>
</div>
<input
ng-if="Question.type === 'text'"
type="{{Question.type}}"
name="institutionName"
class="inputName"
value="{{Question.value}}"
ng-model="value"
ng-minlength="{{Question.min}}"
ng-maxlength="{{Question.max}}"
ng-keypress="enter($event,value)"
placeholder="{{Question.placeholder}}"
ng-pattern="{{Question.pattern}}" />
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.minlength || addForm.institutionName.$error.maxlength">
Minimum {{Question.min}} znaków
</div> -->
<!-- <div class="custom-error institution" ng-show="addForm.institutionName.$error.maxlength">
Max {{Question.max}} znaków
</div> -->
<div class="custom-error institution" ng-show="addForm.institutionName.$error.pattern || addForm.institutionName.$error.maxlength || addForm.institutionName.$error.minlength">
{{Question.copy}}
</div>
</div>
</form>
</div>
<p>
{{lang.sec101.title2}}
</p>
<a href="rejestracja_10edit.html" class="btn btn-lg btn-default bt_edit" type="button">
{{lang.sec101.title3}}<span class="btn_bg_img"></span>
</a>
</div>
<div class="col-md-12 noPad" ng-repeat="sek in formOut">
<h3 class="daneHeading">{{sek.name}}</h3>
<div class="row">
<div class="col-md-12" >
<div class="col-md-4 col-sm-6 boxContent3 boxes" ng-repeat="row in sek.data">
<span class="leftBoxContrnt">{{row.shortAsk}}</h4></span>
<h4 class="rightBoxContrnt">{{row.value}}</h4>
</div>
</div>
</div>
</div>
<!-- <div class="row col-md-12" >
<h3 class="daneHeading">Hasło</h3>
</div>
<div class="row">
<div class="col-md-12 " >
<div class="col-md-4 col-sm-6 boxContent3">
<span class="leftBoxContrnt">Test</h4></span><span class="blueTxt"> *</span>
<h4 class="rightBoxContrnt">Test</h4>
</div>
</div>
</div> -->
</div>
my controller:
var app = angular.module('app', ['ngAnimate', 'ngCookies', 'ui.bootstrap', 'ngSanitize', 'nya.bootstrap.select', 'jackrabbitsgroup.angular-slider-directive']);
// var rej10_Controller = function($scope, $http, $cookieStore, $timeout, limitToFilter) {
app.controller('rej10_Controller', ['$scope', '$http', '$cookieStore', '$sce', '$timeout', 'limitToFilter',
function($scope, $http, $cookieStore, $sce, $timeout, limitToFilter) {
var view = 10,
arr,
data,
counterSection = 0,
counterAsk = 0;
$scope.opts = {};
$scope.slider_id = 'my-slider';
$scope.opts = {
'num_handles': 1,
'user_values': [0, 1],
'slider_min': 0,
'slider_max': 1,
'precision': 0,
};
/* language */
if (!$cookieStore.get('lang'))
$cookieStore.put('lang', 'pl');
var lang = $cookieStore.get('lang');
$scope.language = lang;
$scope.setLang = function(data) {
$cookieStore.put('lang', data);
$http.get('../widoki/json/lang/' + data + '/rej_' + view + '.json').
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn.sekcja[counterSection].data[counterAsk];
console.log($scope.lang);
}).
error(function(data, status, headers, config) {
console.log('error load json');
});
$scope.language = data;
};
/* get language pack */
$http({
method: 'GET',
url: '../widoki/json/lang/' + lang + '/rej_' + view + '.json'
}).
success(function(data, status, headers, config) {
$scope.lang = data;
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
$scope.langLen = $scope.lang.formIn.length;
}).error(function(data, status, headers, config) {
console.log('error load json');
});
/* dynamic form */
$scope.enter = function(ev, d) {
if (ev.which == 13) {
$scope.addData(d);
}
};
$scope.addData = function(data) {
var newData = {};
/* latamy po id sekcji i po id pytania */
if (!$scope.formOut) {
$scope.formOut = [];
}
/* budowanie modelu danych wychodzcych */
newData = {
sekcja: counterSection,
name: $scope.lang.formIn[counterSection].name,
data: []
};
console.log(name);
if (!$scope.formOut[counterSection]) {
$scope.formOut.push(newData);
}
$scope.formOut[counterSection].data.push($scope.Question);
$scope.formOut[counterSection].data[counterAsk].value = data;
counterAsk++;
// zmieniamy sekcje
if (counterAsk == $scope.lang.formIn[counterSection].data.length) {
counterAsk = 0;
counterSection++;
}
if (counterSection == $scope.lang.formIn.length) {
$scope.Question = '';
/* zrobic ukrycie pola z formularza */
} else {
$scope.Question = $scope.lang.formIn[counterSection].data[counterAsk];
}
/* konwertowanie do jsona */
//var Json = angular.toJson($scope.formOut);
//console.log(Json);
};
$scope.submit = function() {
alert('form sent'); /* wysĹanie formularza */
};
$scope.getClass = function(b) {
return b.toString();
};
}
]);
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
app.config(['$tooltipProvider',
function($tooltipProvider) {
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave',
'show': 'hide'
});
}
]);
var ValidSubmit = ['$parse',
function($parse) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function postLink(scope, element, iAttrs, controller) {
var form = element.controller('form');
form.$submitted = false;
var fn = $parse(iAttrs.validSubmit);
element.on('submit', function(event) {
scope.$apply(function() {
element.addClass('ng-submitted');
form.$submitted = true;
if (form.$valid) {
fn(scope, {
$event: event
});
}
});
});
scope.$watch(function() {
return form.$valid
}, function(isValid) {
if (form.$submitted == false)
return;
if (isValid) {
element.removeClass('has-error').addClass('has-success');
} else {
element.removeClass('has-success');
element.addClass('has-error');
}
});
}
};
}
};
}
];
app.directive('validSubmit', ValidSubmit);
I cant figure out what is the problem.
Thanks in advance.
Try changing your ngClick button handler to an ngSubmit form handler and wiring that up. You didn't say what browser you're using, but most of them auto-submit forms on an ENTER keypress unless you trap it (which you aren't). Clicking a button won't do this.

Resources