I am a beginner in anular.js. I'm trying to write a code which add and removes rows in a table on button click and once done ad user clicks on createdelivery button I want to send the data as a JSON object to server.
But when am injecting $http as follows,
var app = angular.module("createDelivery", []);
app.controller("MyController", ['$scope', 'http', function($scope, $http)
it doesn't create the table also.
Please help me to solve the issue.
<html>
<head>
<title>Add Rows</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script>
var app = angular.module("createDelivery", []);
app.controller("MyController", ['$scope', 'http', function($scope, $http) {
$scope.deliveryDetails = [
{
'fname':'Muhammed',
'lname':'Shanid',
'email':'shanid#shanid.com'
},
{
'fname':'Roy',
'lname':'Mathew',
'email':'roy#roy.com'
}];
$scope.addNew = function(cdDetails){
$scope.deliveryDetails.push({
'fname': "",
'lname': "",
'email': "",
});
};
$scope.remove = function(){
var newDataList=[];
$scope.selectedAll = false;
angular.forEach($scope.deliveryDetails, function(selected){
if(!selected.selected){
newDataList.push(selected);
}
});
$scope.deliveryDetails = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.deliveryDetails, function(cdDetails) {
cdDetails.selected = $scope.selectedAll;
});
};
$scope.getData = function(cdDetails)
{
alert("Check");
var jsonString;
jsonString = angular.toJson(cdDetails);
//JSON.stringify(jsonString);
$http
({
url: "/scheduler/createDelivery",
dataType: 'json',
method: 'POST',
data: jsonString
}).success(function(response) {
alert("success : : "+jsonString);
$scope.value = response;
}).error(function(error) {
alert("error::"+error);
});
//window.location.reload();
//document.write("\nString value "+jsonString);
};
}]);
</script>
</head>
<body ng-app="createDelivery" ng-controller="MyController">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form ng-submit="addNew()">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" /></th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cdDetails in deliveryDetails">
<td>
<input type="checkbox" ng-model="cdDetails.selected"/></td>
<td>
<input type="text" class="form-control" ng-model="cdDetails.fname" required/></td>
<td>
<input type="text" class="form-control" ng-model="cdDetails.lname" required/></td>
<td>
<input type="email" class="form-control" ng-model="cdDetails.email" required/></td>
</tr>
</tbody>
</table>
<div class="form-group">
<input ng-hide="!deliveryDetails.length" type="button" class="btn btn-danger pull-right" ng-click="remove()" value="Remove">
<input type="submit" class="btn btn-primary addnew pull-right" value="Add New">
<button type="button" name = "createDelivery"class="col-sm-2 btn btn-primary" style="width:25%" ng-click="getData(cdDetails);">Create Delivery</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
app.controller("MyController", ['$scope', 'http'
One mistake in code is above. Change it and try. you must inject $http
Related
so following is my Dynamically created template, it has an issue, when i add my template, it brings values from the previous DOM. Where was i want new to be empty.
Following is my HTML file, and my-custom-row-template is where i am repeating my template, now i assume that $index will create a new index, and values/DOM wouldn't repeat.
<section class="main_container">
<div class="container">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form ng-submit="addNew()">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th><input type="checkbox" ng-model="selectedAll" ng-click="checkAll()"/></th>
<th scope="col">Setup Responses</th>
<th>Add Condition</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="personalDetail in personalDetails">
<td scope="col">
<input type="checkbox" ng-model="personalDetail.selected"/>
</td>
<td scope="col" class="col-xs-10">
<div ng-repeat="condition_set in conditions track by $index" my-custom-row-template></div>
</td>
</td>
<td scope="col">
<input type="button" value="Add Condition" ng-click="addCondition()"
class="btn btn-primary addnew"/>
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<input ng-hide="!personalDetails.length" type="button"
class="btn btn-danger pull-right"
ng-click="remove()" value="Remove">
<input type="button" class="btn btn-primary addnew pull-right" value="Add New" ng-click="addNew()">
<input type="submit" class="btn btn-primary pull-right" value="Save">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
</span>
And this is my template code
<div class="col-xs-8 pull-left">
<div class="row form-group">
<!--<select ng-model="response.condition" style="color: black;">-->
<!--<option>Response Message</option>-->
<!--<option>IF</option>-->
<!--<option>Else</option>-->
<!--</select>-->
<select ng-model="selectedCondition[$index]">
<option ng-repeat="x in conditions.condition_set" value="{{x.name}}">{{x.value}}</option>
</select>
<input ng-show="selectedCondition=='0'" type="text" class="form-control"
ng-model="personalDetail[$index].message"/>
<input ng-show="selectedCondition=='1'" type="text" class="form-control"
ng-model="conditions[$index].response"/>
<input ng-show="selectedCondition=='2'" type="text" class="form-control"
ng-model="conditions[$index].elseMessage"/>
<select ng-show="selectedCondition=='1'" ng-model="goToStepOrNew">
<option ng-repeat="x in conditions[$index].create_new_conditions" value="{{x.name}}">{{x.value}}</option>
</select>
<input type="button" value="Remove Condition" ng-click="remove_condition($index)" class="btn btn-danger"/>
</div>
</div>
And this is how i am handling it within my controller
$http({
method: "POST",
url: "team_lead_showed_contacts/ajax",
data: $.param(obj),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformResponse: [function (data) {
var str = '';
str = data.toString();
str = str.replace(/\\/g, 0);
return str;
}]
}).then(function (response) {
//debugger;
$scope.campaigns = JSON.parse(response.data);
$scope.personalDetails = [
{
'add_tempalte': '<div my-custom-row-template> </div>',
}
];
$scope.addNew = function (personalDetail) {
$scope.personalDetails.push({
'add_template': '<div my-custom-row-template> </div>',
});
};
function triggerNewRow($scope) {
if ($scope.goToStepOrNew == 0) {
}
}
$scope.remove = function () {
var newDataList = [];
$scope.selectedAll = false;
angular.forEach($scope.personalDetails, function (selected) {
if (!selected.selected) {
newDataList.push(selected);
}
});
$scope.personalDetails = newDataList;
};
$scope.checkAll = function () {
if (!$scope.selectedAll) {
$scope.selectedAll = true;
} else {
$scope.selectedAll = false;
}
angular.forEach($scope.personalDetails, function (personalDetail) {
personalDetail.selected = $scope.selectedAll;
});
};
$scope.conditions = [];
$scope.conditions.push('myCustomRowTemplate');
$index = 0;
$scope.addCondition = function () {
$scope.conditions.push('myCustomRowTemplate');
};
$scope.conditions.condition_set = [
{name: 0, value: 'Response Message'},
{name: 1, value: 'IF'},
{name: 2, value: "ELSE"}
];
$scope.conditions.create_new_conditions = [
{name: 0, value: 'Create Step'},
];
$scope.remove_condition = function (element) {
$scope.conditions.splice(element, 1);
// console.log(element);
};
});
For Reference i am attaching an image to give an idea, to what happens when i copy Add New. Copy of already present Elements is pushed into the DOM.
EDIT
Tried some thing like this following Kinda same issue like this post
but no effect.
$scope.personalDetails = [
{
'add_template': '<div my-custom-row-template> </div>',
}
];
var newStep = angular.copy($scope.personalDetails);
$scope.addNew = function (personalDetail) {
$scope.personalDetails.push(
newStep
);
};
I am new to angular and I tried to create a application to add, update and delete information about the lab test. But when the page is loaded one error occurrs. If anybody knows the reason for this please help me. Thank you.
Error
enter image description here
ManageLabTest.html
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="UTF-8">
<title>Lab Test Management</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Dynatable/0.3.1/jquery.dynatable.css">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-sweetalert/1.0.1/sweetalert.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<script src="../app.module.js"></script>
<script src="../Controller/LabController.js"></script>
<script src="../Controller/main.route.js"></script>
</head>
<body ng-controller="ManageLabTest">
<div id="page">
<div class="header"><img src="../img/logoPCU%20(2).jpg" height="174" width="721"/>
<h1 class="text-info">Lab Test Details Management</h1>
</div>
</div>
<div class="container">
<div class="navigation">
<div class="page-header">
</div>
<div class="well well-lg">
<div class="container-fluid">
<h3><strong>Lab Test Details</strong></h3>
<div class="row">
<div class="col-md-12">
<div class="col-md-4">
<div class="form-group">
<label>Patient ID </label>
<input type='text' class="form-control" ng-model="Test.patientID"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Test Code</label>
<input type='text' class="form-control"ng-model="Test.testCode" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Test Name</label>
<input type='text' class="form-control" ng-model="Test.testName"/>
</div>
</div>
<div class="container">
<div class='col-md-3 '>
<div class="form-group">
<label>Type</label>
<select ng-model="Test.type" class="form-control">
<option>Select Type</option>
<option>Critical</option>
<option>Non-Critical</option>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label>Date</label>
<div ng-model="Prescription.date">{{date | date:'yyyy-MM-dd'}}</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group pull-right" ng-submit="addNew()">
<input type="submit" class="btn btn-primary addnew pull-right" value="Add New"/>
<button class="btn btn-warning" id="clear" ng-click="clear()" onclick="enableAddButton()">
Clear
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="page-header">
<h3><strong>Add Lab Test</strong></h3>
</div>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="data-table2">
<tr>
<th> Patient ID </th>
<th> Type </th>
<th> Test Code </th>
<th> Test Name </th>
<th> Date</th>
<th> Edit </th>
<th> Delete</th>
</tr>
<tr ng-repeat="Test in Tests">
<td> {{Test.patientID}} </td>
<td> {{Test.type}} </td>
<td> {{Test.testCode}} </td>
<td> {{Test.testName}} </td>
<td> {{Test.date}} </td>
<td>
<button class="btn btn-warning btn-sm" ng-click="editLab(Test._id)"
onclick="enableUpdateButtons()">Edit <span
class="glyphicon glyphicon-pencil"></span></button>
</td>
<td>
<button class="btn btn-danger btn-sm" ng-click="deleteLab(Test._id)">Delete <span
class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group pull-right">
<button class="btn btn-success btn-sm" ng-click="" onclick="">Save/Send</button>
</div>
</div>
</div>
<div class="page-header">
<h3><strong>Lab Test Details</strong></h3>
</div>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-bordered table-hover" id="data-table">
<tr>
<th> Patient ID </th>
<th> Type </th>
<th> Test Code </th>
<th> Test Name </th>
<th> Date</th>
<th> Edit </th>
<th> Delete</th>
</tr>
<tr ng-repeat="Test in Tests">
<td> {{Test.patientID}} </td>
<td> {{Test.type}} </td>
<td> {{Test.testCode}} </td>
<td> {{Test.testName}} </td>
<td> {{Test.date}} </td>
<td>
<button class="btn btn-warning btn-sm" ng-click="editLab(Test._id)"
onclick="enableUpdateButtons()">Edit <span
class="glyphicon glyphicon-pencil"></span></button>
</td>
<td>
<button class="btn btn-danger btn-sm" ng-click="deleteLab(Test._id)">Delete <span
class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group pull-right">
<button class="btn btn-success btn-sm" ng-click="" onclick="">Save changers</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
LabController.js
'use strict';
angular.module('app').controller('ManageLabTest', ['$scope', function ($scope) {
getLab();
function getLab() {
$http.get('/').then(response => {
$scope.labs = labs;
$scope.lab = null;
});
};
$scope.clear=function(){
$scope.lab=null;
};
$scope.addLab = () => {
$http.post('/',$scope.lab).then(function(response){
getLab();
});
};
$scope.update = () =>{
$http.put('/'+$scope.lab._id,$scope.lab).then(function(response){
getLab();
clear();
});
};
$scope.edit = () =>{
$http.get('/'+id).then(function(response){
$scope.lab = response.data;
});
};
$scope.remove = () =>{
$http.delete('/'+id).then(function(response){
getLab();
});
};
$scope.Test = [];
$scope.addNew = function (Test) {
$scope.Test.push({
'patientID':"",
'testCode':"",
'testName':"",
'date':""
});
};
$scope.date = new Date();
}]);
Lab.model.js
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const LabTestSchema = new Schema({
patientID: {
type: String,
required: true
},
testCode: {
type: String,
required: true
},
testName: {
type: String,
required: true
},
date: {
type: Date,
required: true
},
type:{
type: String,
required: true
}
});
var LabTest = mongoose.model('LabTest', LabTestSchema);
module.exports = LabTest;
app.module.js
angular.module('app',['ngRoute']);
server.js
const bodyParser = require('body-parser'),
express = require('express'),
mongoose = require('mongoose');
mongoose.Promise = global.Promise;
require('./Interface/DataModel/prescription.model.js');
require('./Interface/DataModel/Lab.model.js');
const PresRouter = require('./Interface/Routers/Prescription.route.js');
const LabRouter = require('./Interface/Routers/Lab.route.js')
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'true'}));
mongoose.connect('mongodb://localhost:27017/PCU', err => {
if (err) {
console.log(err);
process.exit(1);
}
}
);
app.use(express.static(__dirname+'/Interface'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/Interface/Pres&Labs/ManageLabTest.html');
});
app.use('/',PresRouter);
app.use('/',LabRouter);
app.listen(3000, err => {
if (err) {
console.error(err);
return;
}
console.log('app listening on port 3000');
});
Lab.route.js
'use strict';
const express = require('express');
const mongoose = require('mongoose');
mongoose.set('debug', false);
const router = express.Router();
const LabModel = require('../DataModel/Lab.model.js');
router.get('/',function (req,res) {
LabModel.find().then(labs => {
res.json(labs);
}).catch(err => {
console.error(err);
res.sendStatus(500);
});
});
router.post('/',function (req,res) {
const lab = new LabModel(req.body);
labs.save().then(labs => {
res.json(labs);
}).catch(err => {
console.error(err);
res.sendStatus(500);
});
});
router.get('/:id',function (req,res) {
LabModel.findById(req.params.id).then(data=>{
res.json(data || {});
}).catch(err=>{
console.error(err);
res.sendStatus(500);
});
});
router.put('/:id',function (req,res) {
const data = req.body;
delete data._id;
const Id = req.params.id;
LabModel.findByIdAndUpdate(Id,{$set:data}).then(db=>{
res.json(data);
}).catch(err => {
console.error(err);
res.sendStatus(500);
});
});
router.delete('/:id',function (req,res) {
LabModel.findByIdAndRemove(req.params.id).then(data=>{
res.sendStatus(200,'success');
});
});
module.exports = router;
main.route.js
angular.module('app').config(['$routeProvider'],function ($routeProvider) {
$routeProvider
.when('/ManagePrescription',{
templateUrl : 'ManagePrescription.html',
controller : 'ManagePrescription'
})
.when('/ManageLabTest',{
templateUrl : 'ManageLabTest.html',
controller : 'ManageLabTest'
})
.when('SearchPrescription',{
templateUrl : 'SearchPrescription.html',
controller : 'ManagePrescription'
})
.when('SearchLabTest',{
templateUrl : 'SearchLabTest.html',
controller : 'ManageLabTest'
});
});
There is syntax error in main.route.js
you are defining your function out of Array..
angular.module('app').config(['$routeProvider'],function ($routeProvider) {
//YOUR LOGIC
});
The code should look like as below
angular.module('app').config(['$routeProvider',function ($routeProvider) {
//YOUR LOGIC
}]);
the pushed data from the model is not reflecting in the first table. It is there in console. The fiddle link is attached with this please help me on this.
fiddle link ---- http://jsfiddle.net/8MVLJ/2649/
html=========
<script src="https://code.angularjs.org/1.4.9/angular.min.js"></script>
<script src="https://rawgit.com/dwmkerr/angular-modal-service/master/dst/angular-modal-service.js"></script>
<div class="container" ng-app="app" ng-controller="Controller">
<div class="row">
<div class="col-xs-12">
<table class="table table-striped table-bordered">
<thead>
<th>Attribute Name</th>
<th>Attribute Value</th>
</thead>
<tbody>
<tr ng-repeat="newdetail in newDetails">
<td>
<p ng-model="detail">{{newdetail.attrName}} </p>
</td>
<td>
<p ng-model="detailValue">{{newdetail.userAttrValue}} </p>
</td>
</tr>
</tbody>
</table>
<a class="btn btn-default" href ng-click="show()">Select Attribute</a>
<script type="text/ng-template" id="modal.html">
<div class=" ngdialog-messsage modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ng-click="close('Cancel')" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<table class="table table-striped table-bordered">
<thead>
<th>
<input type="checkbox" ng-model="allSelected" ng-model-options="{getterSetter: true}">
</th>
<th>Attribute Name</th>
<th>Attribute Value</th>
</thead>
<tbody>
<tr ng-repeat="detail in details">
<td>
<input type="checkbox" ng-model="detail.Selected">
</td>
<td>
<p ng-model="detail">{{detail.attrName}}</p>
</td>
<td>
<select ng-model="detail.user_attr_value" ng-init="detail.user_attr_value=detail.attr_value_Ind.split(',')[0]" class="form-control full-width">
<option ng-repeat="option in detail .attr_value_Ind.split(',')" value="{{option}}">{{option}}</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<input type="button" class="btn btn-primary" value="Add Selected" ng-click="add();close('Cancel')">
<input type="button" class="btn btn-danger " ng-click="checkAll(details.length)" value="Clear">
</div>
</div>
</div>
</div>
</div>
</script>
</div>
</div>
</div>
js===================
var app = angular.module('app', ['angularModalService']);
app.controller('Controller', function($scope, $element, ModalService) {
$scope.newDetails = [{
"attrName": "userType",
"userAttrValue": "Customer",
"userOrGroupId": "aaaazzz8522",
}];
$scope.add = function() {
angular.forEach($scope.details, function(detail) {
if (detail.Selected == true) {
$scope.newDetails.push({
'attrName': detail.attrName,
'attrName': detail.user_attr_value
});
$element.modal('hide');
close($scope.newDetails, 500);
console.log("loop", $scope.newDetails);
}
});
};
$scope.show = function() {
ModalService.showModal({
templateUrl: 'modal.html',
controller: "Controller"
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {});
});
};
//=================================================
$scope.close = function(result) {
close(result, 600);
};
$scope.details = [{
"attrName": "region",
"attrType": "USER",
"attr_value_Ind": "CHN-N,CHN-S,CHN-C",
"buId": "DEFAULT",
}];
var getAllSelected = function() {
var selecteddetails = $scope.details.filter(function(detail) {
return detail.Selected;
});
return selecteddetails.length === $scope.details.length;
}
var setAllSelected = function(value) {
angular.forEach($scope.details, function(detail) {
detail.Selected = value;
});
}
$scope.allSelected = function(value) {
if (value !== undefined) {
return setAllSelected(value);
} else {
return getAllSelected();
}
}
$scope.checkAll = function(Count) {
angular.forEach($scope.details, function(details) {
details.Selected = false;
});
};
});
i have updated your fiddle please check and review.http://jsfiddle.net/8MVLJ/2652/
it's not pushing it's value because you have pass scope in your modal controller and set parent scope like this
ModalService.showModal({
templateUrl: 'modal.html',
controller: "Controller",
scope:$scope <-- added here scope
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {});
});
and add $parent to push your value like this
$scope.$parent.newDetails.push({ <-- added $parent here
'attrName': detail.attrName,
'userAttrValue': detail.user_attr_value
});
I have been stuck in something simple that I think I haven't solved yet because of a lack of experience. Here is the catch I have a very simple controller which load the data from a service when I first Load the modal but once I tried to use the CRUD operations (hopefully working!!) the datatable doesn't update. I will share the code. Thanks of all.
I need that after insert, for example, the datatable update meaning rerender the current list of elements.
Call of the Modal
vm.openBooksModal = function (authorId) {
var modalInstance = $uibModal.open({
templateUrl: '/app/book/index.html,
controller: 'BooksController',
size: '',
resolve: {
authorId: function () {
return authorId;
}
}
});
Modal Controller
(function () {
'use strict';
angular.module('bookApp').controller('BooksController', BooksController);
BooksController.$inject = ['$uibModalInstance', '$scope', 'authorId', 'bookService', 'DTOptionsBuilder', 'DTColumnDefBuilder',
'DTColumnBuilder', 'dtUtils','alertService'];
function NotesController($uibModalInstance, $scope, authorId, bookService, DTOptionsBuilder, DTColumnDefBuilder,
DTColumnBuilder, dtUtils, alertService) {
$scope.authorId= authorId;
$scope.book= {
id: 0,
title:''
};
//if (angular.isDefined())
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
$scope.dtBooksColumnDefs = [
DTColumnDefBuilder.newColumnDef(0).notSortable()
];
$scope.dtBooksOptions = DTOptionsBuilder
.newOptions()
.withOption('bFilter', false)
.withOption('order', [[2, 'desc']])
.withOption('aaSorting', [])
.withOption('lengthMenu', [[5, 10, 25, 50], [5, 10, 25, 50]]);
$scope.dtBooksInstance = {};
$scope.LoadData = LoadData();
function LoadData(){
return bookService.getBook($scope.authorId).$promise
.then(getBookCompleted, handleError);
}
$scope.save = function (newTitle) {
$scope.book.title= newTitle;
bookService.saveBook($scope.book.id, $scope.authorId, $scope.book.title).$promise
.then(saveBookCompleted, handleError);
LoadData();
}
$scope.editBook= function( book){
$scope.book= book;
$scope.newTitle= book.title;
}
$scope.deleteBook = function( book){
bookService.deleteBook(book.id).$promise
.then(saveBookCompleted, handleError);
}
//private methods
function getBookCompleted(data) {
$scope.leadBookList = data;
debugger;
if (angular.isDefined($scope.dtBookInstance.rerender)) {
$scope.dtBooksInstance.rerender();
}
$scope.book= { };
$scope.newTitle = '';
}
function saveBookCompleted() {
bookService.getBook($scope.authorId).$promise
.then(getBookCompleted, handleError);
}
function handleError(response) {
alertService.error("Error trying to add a Note. Please try again later or contact IT.");
}
}
})();
HTML TEMPLATE
<div class="modal-header">
<h3 class="modal-title">Books</h3>
</div>
<div class="modal-body">
<div class="book-container">
<div class="head">
</div>
<div class="book">
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<label class="control-label">{{headerLabel}}</label>
<textarea id="newTitle" class="comment-textarea" data-ng-model="newTitle" rows="8" cols="90"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<table id="tblBooks" datatable="ng" class="table table-striped table-bordered font-xs"
dt-options="dtBookOptions" dt-column-defs="dtBookColumnDefs" >
<thead>
<tr>
<th></th>
<th></th>
<th>Title</th>
<th>Created By</th>
<th>Created Date</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in BookList">
<td>
<button class="btn btn-sm btn-warning" ng-click="editBook(book)">
<i class="fa fa-pencil"></i>
</button>
</td>
<td>
<button class="btn btn-sm btn-danger" ng-click="deleteBook(book)">
<i class="fa fa-trash-o"></i>
</button>
</td>
<td>{{book.title}}</td>
<td>{{book.createdBy}}</td>
<td>{{book.createdDate | date:'MM/dd/yyyy HH:mm:ss'}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer margin-top-0">
<button class="btn btn-primary" ng-click="save(newBook)" data-ng-disabled="newTitle === ''">Save</button>
<button class="btn btn-primary" ng-click="cancel()">Close</button>
</div>
Thanks
You're calling getBookCompleted twice. First after save in the saveBookCompleted function and second in the loaddata function
$scope.save = function (newTitle) {
$scope.book.title= newTitle;
bookService.saveBook($scope.book.id, $scope.authorId, $scope.book.title).$promise
.then(saveBookCompleted, handleError);
// remove this line since you're already call saveBookCompleted
//LoadData();
}
I think i have some pretty big holes in my code, as when the modal is appearing, the content from the table (which when you click on a row produces the modal), is not populating the input boxes I have inside of the modal. I think I'm tackling the situation in the wrong way and some direction would be fantastic.
My JS:
var app = angular.module('peopleInformation', ['ngAnimate','ui.bootstrap']);
app.controller('myCtrl', function($scope, $http, $uibModal) {
$http.get("Assignment005.json").success(function(response){
$scope.myData = response.People;
});
$scope.modify = function(currentData){
var modalInstance = $uibModal.open({
animation: true,
templateUrl: 'myModalContent.html',
controller:function($scope, $uibModalInstance, details){
$scope.FirstName = details.FirstName;
$scope.LastName = details.LastName;
$scope.Age = details.Age;
$scope.Nickname = details.Nickname;
$scope.update = function () {
$uibModalInstance.dismiss('cancel');
};
},
size: 'lg',
resolve: {
details: function() {
return currentData;
}
}
});
};
});
My modal:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Your row of data</h4>
</div>
<div class="modal-body" name="modelData" style="height:200px">
<form class="form-horizontal pull-left form-width" role="form">
<div class="form-group">
<label class="control-label col-sm-4" for="first">First Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="first" ng-model="FirstName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="last">Last Name:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="last" ng-model="LastName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="age">Age:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="age" ng-model="Age">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-4" for="nick">Nickname:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="nick" ng-model="Nickname">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-success pull-right" data-dismiss="modal">Submit</button>
</div>
</div>
Main HTML in case it's needed:
<body>
<div data-ng-app="peopleInformation" data-ng-controller="myCtrl" class="jumbotron">
<div class="panel panel-default">
<div class="panel-heading">Essential Information</div>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Nickname</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="details in myData" data-ng-click="modify(details)">
<td>{{ details.FirstName }}</td>
<td>{{ details.LastName }}</td>
<td>{{ details.Age }}</td>
<td>{{ details.Nickname }}</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-info pull-right" data-ng-click="new()">Add
</button>
</div>
</div>
<div ng-include="myModalContent.html"></div>
</div>
</body>
Im very new to using Angular so if you could be overtly simple with me that would help to clarify things, although again, any help is appreciated.
Bellow is the angular modal instance controller
app.controller('ModalInstanceCtrl', function ($scope,
$uibModalInstance, item) {
$scope.customer = item;
$scope.yes = function () {
$uibModalInstance.close(); };
$scope.no = function () {
$uibModalInstance.dismiss('cancel');
};
});
bellow is the code for call angular modal
$scope.open = function (item) {
var modalInstance = $uibModal.open({
animation: true,
scope: $scope,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
size: 'md',
resolve: {
item: function () {
return item;
}
}
});
modalInstance.result.then(function (selectedItem) {
$log.info(selectedItem);
});
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
Bellow is code for template
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">Re-calculate retail price</h3>
</div>
<div class="modal-body">
Margin percent of selected customer is <b>{{ customer.margin_percent }}</b> <br />
Do you want to recalculate the retail price?
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="yes()">Yes</button>
<button class="btn btn-warning" type="button" ng-click="no()">No</button>
</div>
</script>
I was actually assigning the values in the wrong place I believe. I moved the:
$scope.FirstName = details.FirstName;
Outside of the var modalInstance variable, and they are now populating the input boxes. If this is messy or not standard then let me know as sometimes the right result is not always the right method. Thanks for those that tried to help, much appreciated.
In your HTML file you are passing different parameter to modify function, It should be equal to the parameter specified in ng-repeat directive.
So in this case this:
<tr data-ng-repeat="data in myData" data-ng-click="modify(details)">
will become:
<tr data-ng-repeat="details in myData" data-ng-click="modify(details)">