How can I Add/Edit on same page in Angular - javascript

There are two types of data I'm displaying on single page, one is Insert form and second is where the data is displayed with the help of Angular dataTables, now what I want to do is when I click on Edit I wana display the Data within the Insert form Fields also change the Save button from Save to Update... I've tried it but I'm getting this error although its displaying the data in console.
controller.js:1356 24
controller.js:1363 Colony 02 2
angular-1.4.8.js:12520 TypeError: Cannot set property 'colony_name' of undefined
NOTE: Insert, Delete, Displaying Data is working fine.
Here is my HTML PAGE
<div class="row-fluid" ng-controller="colony_Controller">
<div class="span12">
<div class="span6">
<!-- WIDGET START -->
<div class="widget TwoWidgetsInOneFix">
<!-- Widget Title Start -->
<div class="widget-title">
<h4><i class="icon-reorder"></i>Add Colony</h4>
<span class="tools">
<!-- -->
</span>
</div>
<!-- Widget Title End -->
<!-- Widget Body Start -->
<div class="widget-body">
<form class="form-horizontal">
<div class="control-group">
<div class="small-bg-half">
<label class="control-label">Colony Name</label>
<div class="controls">
<input type="text" class="input-xlarge" id="" autofocus required name="colony_name"
ng-model="field.colony_name" > <!-- ng-->
<span class="help-inline" id="help-inline" style="color:red;"></span>
</div>
</div>
</div>
<div class="control-group">
<div class="small-bg-half">
<label class="control-label">Colony Type</label>
<div class="controls">
<select data-toggle="status" class="select select-default mrs mbm input-xlarge" name="colony_type" id="colony_type" ng-model="field.colony_type_id" required> <!-- ng -->
<option value="">--Select Colony Type--</option>
<option ng-repeat="colony in es_colony_type" value="{{colony.es_colony_type_id}}">{{colony.es_colony_type_name}}</option>
</select>
</div>
</div>
</div>
<div class="form-actions">
<button type="button" class="btn btn-success" ng-click="InsertData()"> <!-- ng -->
<i class="icon-plus icon-white"></i> Save</button>
</div>
</form>
</div>
<!-- Widget Body End -->
</div>
<!-- WIDGET END -->
</div>
<div class="span6">
<!-- WIDGET START -->
<div class="widget TwoWidgetsInOneFix">
<!-- Widget Title Start -->
<div class="widget-title"> <!-- ng -->
<h4><i class="icon-reorder"></i>List Of Colony</h4>
<span class="tools">
<!-- -->
</span>
</div>
<!-- Widget Title End -->
<!-- <div id="alert-2" flash-alert active-class="in alert" class="fade">
<strong class="alert-heading">Boo!</strong>
<span class="alert-message">{{flash.message}}</span>
</div> -->
<!-- Widget Body Start -->
<div class="widget-body">
<div ng-controller="colony_Controller as Main_Module">
<table class="table table-striped table-bordered" align="center" datatable="" dt-options="Main_Module.dtOptions" dt-columns="Main_Module.dtColumns" class="row-border hover">
</table>
</div>
</div>
</div>
<!-- Widget Body End -->
</div>
<!-- WIDGET END -->
</div>
Here is my Controller
Main_Module.controller('colony_Controller', function add_house_Controller(flash, $window, $scope, $http, $compile, DTOptionsBuilder, DTColumnBuilder, bootbox, SimpleHttpRequest, DelMainRecPicRecUnlinkPic, message)
{
$http.get('http://localhost:3000/api/SELECT/es_colony_type').success(function(data)
{
$scope.es_colony_type = data.es_colony_type;
});
/********************************** FETCH DATA END *********************************/
/********************************** INSERT DATA START ********************************/
$scope.InsertData = function()
{
var values = $scope.field;
SimpleHttpRequest.Insert('POST','INSERT', 'es_colony', values)
.then(function successCallback(response)
{
if(!response.data.Error)
{
message.successMessageForInsert("<strong>Successfull !</strong> Colony Details Inserted");
setTimeout(function()
{
$window.location.reload();
}, 3500);
// flash.to('alert-1').success = 'Only for alert 1';
}
else
{
message.failedMessageForInsert("<strong>Error !</strong> Data Insertion Failed");
}
},
function errorCallback(response)
{
message.failedMessageForInsert("<strong>Error!</strong> Data Insertion Failed !");
});
};
/********************************** INSERT DATA END **********************************/
/********************************** DISPLAY DATA START *******************************/
var vm = this;
vm.dtOptions = DTOptionsBuilder
.fromFnPromise(function()
{
return $http.get('http://localhost:3000/api/SELECT/es_colony')
.then(function(response)
{
return response.data.es_colony;
});
})
.withOption('order', [0, 'asc'])
.withDisplayLength(5)
.withPaginationType('simple_numbers')
.withOption('createdRow', function(row, data, dataIndex)
{
$compile(angular.element(row).contents())($scope);
})
vm.dtColumns =
[
DTColumnBuilder.newColumn('es_colony_name').withTitle('Colony'),
DTColumnBuilder.newColumn(null).withTitle('Actions').notSortable().withOption('width', '31%')
.renderWith(function(data, type, full, meta)
{
return '<button class="btn btn-primary" ng-click="edit_records(' + data.es_colony_id + ')">' +
'<i class="icon-edit"></i> Edit' + '</button> ' +
'<button class="btn btn-danger" ng-click="DeleteRecord(' + data.es_colony_id + ')">' +
'<i class="icon-remove icon-white"></i> Delete' + '</button>';
})
];
/********************************** DISPLAY DATA END *********************************/
/********************************** DELETE DATA START ********************************/
// $scope.hideRow = [];
$scope.DeleteRecord = function(id)
{
bootbox.confirm("Are you sure you want to delete this Record ?", function (confirmation)
{
if(confirmation)
{
DelMainRecPicRecUnlinkPic.DeleteIt('', id, true, 'es_colony', 'es_colony_id')
{
setTimeout(function()
{
$window.location.reload();
}, 3500);
};
}
});
};
$scope.edit_records = function(id)
{
// PassId.id = id;
console.log(id);
SimpleHttpRequest.SelectByID('GET', 'SELECTBYID', 'es_colony', 'es_colony_id', id)
.then(function successCallback(response)
{
var data = response.data.es_colony[0];
console.log(data.es_colony_name, data.es_colony_type_id);
$scope.ufield.ucolony_name = data.es_colony_name;
$scope.ufield.colony_type_id = data.es_colony_type_id;
});
};
/********************************** DELETE DATA END **********************************/
});

In your template, you have an input with ng-model="field.colony_name", but in your controller you never defined $scope.field. You do assign the value var values = $scope.field inside the $scope.InsertData function, but that will just set values to undefined.
Try initializing the variable by adding $scope.field = {} to the beginning of your controller, for starters. That will resolve the error you are getting.

Here is the code that may help you.
Html:
<div ng-app="myApp" ng-controller="MainCtrl">
<fieldset data-ng-repeat="choice in choices">
<input type="text" ng-model="choice.name" name="" placeholder="Enter mobile number"> <button class="remove" ng-show="$last" ng-click="removeChoice()">-</button>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
<div id="choicesDisplay">
{{ choices }}
</div>
</div>
Js:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.choices = [{id: 'choice1'}, {id: 'choice2'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
$scope.removeChoice = function() {
var lastItem = $scope.choices.length-1;
$scope.choices.splice(lastItem);
};
});
Also CSS:
fieldset{
background: #FCFCFC;
padding: 16px;
border: 1px solid #D5D5D5;
}
.addfields{
margin: 10px 0;
}
#choicesDisplay {
padding: 10px;
background: rgb(227, 250, 227);
border: 1px solid rgb(171, 239, 171);
color: rgb(9, 56, 9);
}
.remove{
background: #C76868;
color: #FFF;
font-weight: bold;
font-size: 21px;
border: 0;
cursor: pointer;
display: inline-block;
padding: 4px 9px;
vertical-align: top;
line-height: 100%;
}
input[type="text"],
select{
padding:5px;
}

Html
<div ng-app="albumShelf">
<div ng-controller="MainCtrl">
<div style="float:left;">
<select ng-options="b.title for b in albums" ng-model="currentAlbum" ng-change="onChange()">
<option value="">New album...</option>
</select>
</div>
<div style="float:left;">
<form>
<input type="text" ng-model="editing.title">
<br>
<input type="text" ng-model="editing.artist">
<br>
<input type="submit" value="{{ currentAlbum.title ? 'Update' : 'Save' }}" ng-click="addOrSaveAlbum()">
</form>
</div>
</div>
</div>
Js:
var app= angular.module('myApp', [])
.controller('MainCtrl', ['$scope', function($scope/*, albumFactory*/) {
$scope.editing = {};
$scope.albums = [
{ id: 1, title: 'Disorganized Fun', artist: 'Ronald Jenkees' },
{ id: 2, title: 'Secondhand Rapture', artist: 'MS MR' }
];
$scope.addOrSaveAlbum = function() {
if ($scope.currentAlbum) {
$scope.currentAlbum.title = $scope.editing.title;
$scope.currentAlbum.artist = $scope.editing.artist;
}else {
$scope.albums.push({ title: $scope.editing.title, artist: $scope.editing.artist });
}
$scope.editing = {};
};
$scope.onChange = function() {
if ($scope.currentAlbum) {
$scope.editing.title = $scope.currentAlbum.title;
$scope.editing.artist = $scope.currentAlbum.artist;
}else {
$scope.editing = {};
}
};
}])

Related

How to reset modal contents?

The process is like this.
A user searches any words in a search form. Ajax calls with the word and gets the data, then it will be showed with the modal.
So, I tried to make modal dynamically with ajax.
But the modal contents didn't change once it called.
1) This is the function include a search form and it calls the modal.
function answer() {
//console.log('answer');
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = `<!-- file form start -->
<!-- file form end -->
<label class="col-md-2 col-form-label">문의내용</label>
<!-- text form start -->
{!! Form::open([ 'route' => ['qnamembercreate', $qnaMemberData->idx], 'method' => 'post', 'files' => true, 'accept-charset' => 'utf-8','class' => 'col-md-10 col-xs-9' ])!!}
<div class="col-sm-6 offset-md-6 p-0">
<div class="input-group">
<input type="text" id="f_search" name="f_search" class="form-control">
<span class="input-group-append">
<button type="button" class="btn waves-effect waves-light btn-inverse" onclick="faq_search()">Search</button>
</span>
</div>
</div>
<input type="hidden" name="subject" value="{{ $qnaMemberData->subject }}">
<textarea id="answer_content" class="mb-0" rows="20" style="width:100%;" name="add_answer"></textarea>
<div class="form-group">
<input name="fileToUpload" type="file" class="filestyle" data-input="false" id="filestyle-1" tabindex="-1" style="display: none;">
<div class="bootstrap-filestyle input-group">
<div style="position: absolute; width: 100%; height: 35.375px; z-index: -1;"></div>
<span class="group-span-filestyle " tabindex="0">
<label for="filestyle-1" style="margin-bottom: 0;" class="btn btn-secondary btn-sm fload-right">
<input type="file" name="fileToUpload" class="filestyle-1" data-placeholder="" data-buttontext="첨부파일" data-buttonname="btn-secondary">
</label>
</span>
</div>
</div>
<button type="button" class="btn btn-danger btn-sm float-right ml-1 mt-1" onclick="history.back()">취소</button>
<button type="submit" class="btn btn-success btn-sm float-right mt-1">등록</button>
{!! Form::close() !!}
<!-- text form end -->`;
document.getElementById('replyData').appendChild(div);
document.getElementById('answer').remove();
$('#answer_content').summernote({
// placeholder: {!! json_encode($qnaMemberData->content) !!},
tabsize: 2,
height: 200,
lang: 'ko-KR',
fontNames: ['Gulim', 'Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', ],
fontNamesIgnoreCheck: ['Gulim'],
});
}
2) This is the 'faq_search' function when the user clicks the 'search' button.
function faq_search() {
var word = $('#f_search')[0].value;
//console.log(word);
$.ajax({
url : '/guidesearch',
type : 'POST',
data : {
keyword: word
},
cache : false,
success : function(data, jqXHR, textStatus) {
console.log(data);
faq_popup(data);
}
});
}
3) This is the 'faq_popup' function which is called after getting the data.
function faq_popup(data) {
var _data = data;
console.log("here", _data);
const appendedDiv = $(`
<div class="modal fade show" tabindex="-1" id="faqModal" role="dialog" style="positon:center;">
<div class="modal-dialog modal-dialog-centered">
<!-- Modal content-->
<div class="modal-content">
<div class="table-responsive">
<table class="table mb-0">
<tbody></tbody>
</table>
</div>
</div>
</div>
</div>
`);
const tbody = appendedDiv.find('tbody')[0];
_data.forEach(({ content, subject }, i) => {
//console.log(i);
const tr = tbody.appendChild(document.createElement('tr'));
tr.innerHTML = `
<th scope="row">${i + 1}</th>
<td><a style="cursor:pointer">${subject}</a></td>
`;
tr.querySelector('a').addEventListener('click', () => getContent(content));
});
$('#modal_place').append(appendedDiv);
$('#faqModal').modal('show');
}
I tried to reset the modal with this code below. But the problem is, once the modal content is cleared, the new data is not called at all.
$(document).ready(function(){
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).find('tbody td').html("");
});
});
I really don't get it. Because I call the 'faq_popup' after the ajax got the data, the new data should be showed. But it doesn't work as I think.
What did I wrong here?
** I also tried to wipe out the whole modal-content. The modal contents doesn't show up at all.
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).find('.modal-content').html("");
});
I found the solution. Thanks to #KaseyChang, gave me the hint.
The reason was I didn't destroy the modal correctly. The modal was added and added on itself. So I just did this.
$('body').on('hidden.bs.modal', '.modal', function () {
console.log("modal closed");
$(this).remove(); <--- here!
});
In the AJAX function you can just empty() the modal before the call is made, using beforeSend. This way it will happen sequentially:
function faq_search() {
var word = $('#f_search')[0].value;
$.ajax({
url : '/guidesearch',
type : 'POST',
data : {
keyword: word
},
cache : false,
beforeSend : function() {
$('.modal-content').empty();
},
success : function(data, jqXHR, textStatus) {
console.log(data);
faq_popup(data);
}
});
}

How to get the id from the database upon clicking the button via ajax

Here is the scenario, I am doing a message thread inside a modal. I want to show a message thread for a specific person using its reference number. My problem is I cannot pass the reference number to my controller and return to my blade (in message thread). Here are my Codes.
My modal for message thread
<div id="threadmessage" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Message Thread</h3>
</div>
<div class="modal-body" style="height: 300px;" >
<div class="row" style=" margin-left: 30px; margin-bottom: 5px; left: 20px; width: 550px; height: 200px; overflow: auto;">
<div>
#foreach ($messageThread as $thread)
{!!$thread->message!!}
<br>
#endforeach
</div>
<br>
</div>
<div>
<br>
<div class="col-md-2">
<b> Message: </b><br>
</div>
<div class="col-md-10">
<textarea required=" " id="messageContent" style="resize: none;" class="form-control" rows="2"></textarea>
</div>
</div>
<br>
</div>
<div class="modal-footer">
<div>
<button type="button" id="btn-message" class="btn btn-default" data-dismiss="modal" style="background-color: #3c5fa6; color: white;">
Send <i class="fa fa-paper-plane-o ml-1"> </i>
</button>
</div>
</div>
</div>
</div>
</div>
My Javasript for showing the message modal
$('#inquire_t tbody').on('click','#showMsg-btn',function(){
var flag = 6; // Approved
var refNumber = $(this).attr('value');
var cur_flag = $(this).attr('name');
var user = $("#username").html();
console.log(refNumber);
console.log(user);
$('#threadmessage').modal({"backdrop":"static"});
getMessage(refNumber, user);
});//btn-message
function getMessage(num, name){
var refNumber = num;
var username = name;
$.ajax({
url:'getAllMessage',
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: refNumber+'refNumber'+username+'&username',
// dataType:'TEXT',
success: function(data){
}
})
}
Button for Modal
"
Controller for getting the messages
public function getAllMessage(Request $request){
$refNumber = $request->get('refNumber');
$number = $refNumber;
$messageThread = DB::table('i_di_thread')->select('message')->where('refNumber', '=', $number)->get();
return view ('message', ['messageThread'=>$messageThread]);
}
My Route
Route::get('showInquiries','HomeController#getAllMessage');
Route::get('getAllMessage','HomeController#getAllMessage');
You can pass it by two methods and your data is not concatenated properly so :
Method 1 :
$.ajax({
...
data : { 'refNumber' : refNumber, 'username' : username },
...
});
Method 2 :
data:'refNumber='+ refNumber + '&username='+ username

how to use pagination in angularjs?

So i am developing this app in which i want to apply pagination to list of templates.
template objects are stored in the list.
I am displaying thumbnails of templates on the page and i want to apply pagination for this page.
so far I have tried following solution but it didn't work.
list.html
<div class="container">
<div class="homepage-header">
<h2 class="homepage-title text-center wow fadeInDown animated" style="visibility: visible; animation-name: fadeInDown; -webkit-animation-name: fadeInDown;"> TEMPLATES </h2>
</div>
<div class="row">
<div class="col-md-6 col-sm-6" style="text-align: left">
<div class="form-inline">
<div class="form-group has-feedback has-clear">
<input type="text" class="form-control" ng-model="searchParam" ng-model-options="{ debounce: 400 }" placeholder="Search template ..."
/>
<a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="searchParam = '';
retreivePageData(0);" ng-show="searchParam" style="pointer-events: auto; "></a>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6" style="text-align: right; padding-right: 30px;">
<div class="form-inline">
<label>
<input type="radio" ng-model="selectedOption" value="All" ng-change="retrieveTemplates(selectedOption)"> All
</label>
<label>
<input type="radio" ng-model="selectedOption" value="Annotate" ng-change="retrieveTemplates(selectedOption)"> Annotate
</label>
<label>
<input type="radio" ng-model="selectedOption" value="Rapid" ng-change="retrieveTemplates(selectedOption)"> Component
</label>
</div>
</div>
</div>
<div class="homepage-ui-showcase-2-css row wow zoomIn animated" style="height: 402px;padding: 5px 0px; visibility: visible; animation-name: zoomIn; -webkit-animation-name: zoomIn;">
<div ng-repeat="(templateIndex, templateModel) in templatesList | filter:searchParam | limitTo: itemsPerPage">
<div class="active col-md-3 col-lg-3 col-sm-6 col-xs-12 mix design painting" style="display: inline-block;padding-top: 10px;"
ng-init="visible=false" ng-mouseover="visible=true" ng-mouseleave="visible=false">
<div class="portfolio-item shadow-effect-1 boxShadow" style="max-width: 250px;padding:0.3px;border:2px dotted #bebede;cursor: pointer">
<div class="mainBadge">
<kbd>{{templateModel.type}}</kbd>
</div>
<div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
<div ng-switch-when="false" style="height: 130px;" ui-sref="/designer/:pageId({pageId:templateModel.id})" class="portfolio-img ">
<i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-puzzle-piece fa-4x"></i>
</div>
<div ng-switch-when="true" style="height: 130px;" ui-sref="annotator/:annotatedTemplateId({annotatedTemplateId:templateModel.id})"
class="portfolio-img ">
<i style="opacity:0.4;padding-top:35px;padding-left:15px;margin-left: 30%;" class="fa fa-file-image-o fa-4x"></i>
</div>
</div>
<div class="portfolio-item-content" title="{{templateModel.name}}">
<h3 class="header" style="font-size: 13px;text-align: center;display:inline;">
{{templateModel.name}}
</h3>
<small class="pull-right" ng-show="visible" style="display: inline; padding-top: 4px">
<div ng-switch on="{{templateModel.type !== undefined && templateModel.type === 'Annotate'}}">
<div ng-switch-when="true" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
ui-sref="generateCommunication({mode:'A',id: templateModel.id})"
ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
<i class="fa fa-file-pdf-o"></i>
</div>
<div ng-switch-when="false" href="#" class="btn btn-xs btn-danger" title="Generate Communication"
ui-sref="generateCommunication({mode:'T',id: templateModel.id})"
ng-disabled="!templateModel.dynamic_entity"> <!--style="color:#9d9d9;"-->
<i class="fa fa-file-pdf-o"></i>
</div>
</div>
</small>
</div>
</div>
</div>
</div>
</div>
<div class="row " style="margin-top: 10px; padding-top:0px;">
<div class="pagination-div pull-right" style="">
<uib-pagination ng-model="currentPage" total-items="totalItems" max-size="maxSize" boundary-links="true">
</uib-pagination>
</div>
</div>
list.controller.js
'use strict';
angular.module('rapid').controller('HomeListController',
function($scope, $rootScope, $window, $uibModal, ServiceFactory, toaster, ReadFileService, AnnotationService, AnnotateService, DocumentService) {
$scope.templatesList = [];
$scope.filteredTemplates = [];
$scope.selectedOption = 'All';
$scope.annotateTemplateMeta = [];
$scope.rapidTemplateMeta = [];
$scope.init = function() {
$scope.selectedOption = "All";
//$scope.options = [{'label':'All', 'value':'All'}, {'label':'Annotate', 'value':'Annotate'}, {'label':'Component', 'value':'Component'}];
$scope.retrieveTemplates('All');
$scope.currentPage = 1;
};
$scope.retrieveTemplates = function(selectedOption) {
$scope.templatesList = [];
if (selectedOption === 'Annotate') {
$scope.fetchAnnotationTemplates(selectedOption);
} else if (selectedOption === 'Rapid') {
$scope.fetchRapidTemplates(selectedOption);
} else {
$scope.fetchAnnotationTemplates(selectedOption);
}
};
$scope.fetchAnnotationTemplates = function(selectedOption) {
AnnotateService.get().$promise.then(function(result) {
$scope.annotateTemplateMeta = result[0];
console.log('Annotated template count :: ' + result[0].length);
if (selectedOption === 'All') {
$scope.fetchRapidTemplates(selectedOption);
} else {
$scope.prepareTemplateList(selectedOption);
}
});
};
$scope.fetchRapidTemplates = function(selectedOption) {
ServiceFactory.PagesService.getAllPages().$promise.then(function(result) {
$scope.rapidTemplateMeta = result[0];
console.log('Rapid template count :: ' + result[0].length);
$scope.prepareTemplateList(selectedOption);
});
};
$scope.prepareTemplateList = function(selectedOption) {
$scope.itemsPerPage = 8;
var getPaginatedTemplateList = 'getList';
//$scope.currentPage = 0;
if (selectedOption === 'Annotate') {
$scope.annotateTemplateMeta.forEach(function(annotate) {
var templateObject = {};
templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity: annotate.dynamic_entity };
$scope.templatesList.push(templateObject);
});
} else if (selectedOption === 'Rapid') {
$scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
var templateObject = {};
templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity: rapidTemplate.pageObj.entity };
$scope.templatesList.push(templateObject);
});
} else {
$scope.annotateTemplateMeta.forEach(function(annotate) {
var templateObject = {};
templateObject = { id: annotate.id, name: annotate.name, type: "Annotate", dynamic_entity: annotate.dynamic_entity };
$scope.templatesList.push(templateObject);
});
$scope.rapidTemplateMeta.forEach(function(rapidTemplate) {
var templateObject = {};
templateObject = { id: rapidTemplate._id, name: rapidTemplate.name, type: "Component", dynamic_entity: rapidTemplate.pageObj.entity };
$scope.templatesList.push(templateObject);
});
$scope.totalItems = $scope.templatesList.length;
$scope.maxSize = 5;
}
console.log($scope.templatesList);
console.log($scope.currentPage);
};
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.pageChanged = function() {
alert('Page changed to: ' + $scope.currentPage);
$log.log('Page changed to: ' + $scope.currentPage);
};
$scope.init();
$scope.$watch('currentPage + numPerPage', function() {
console.log('is it coming.....?');
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage)
, end = begin + $scope.itemsPerPage;
$scope.filteredTemplates = $scope.templatesList.slice(begin, end);
});
});
is there anything wrong with my code?
please provide some inputs on this.
See how to create a custom paging which will deal with the performance and you will have control on the paging control style.
Create a service to set a paging object
var rapid = angular.module('rapid');
rapid.service('pagerOptions', function () {
'use strict';
return {
newOptions: function () {
return {
totalItems: 0,
itemsPerPage: 50,
page: 1,
sortBy: '',
isASC: true,
filters: null,
sortOptions: {
by: '',
isASC: true,
sort: function (sortBy) {
if (sortBy === this.parent.sortBy) {
this.parent.isASC = !this.parent.isASC;
} else {
this.parent.sortBy = sortBy;
this.parent.isASC = true;
}
this.parent.resetPage();
if (typeof this.parent.onPageChange === "function")
this.parent.onPageChange();
}
},
resetPage: function () {
this.page = 1;
},
goToPage: function (page) {
this.page = page;
if (typeof this.onPageChange === "function")
this.onPageChange();
},
init: function () {
this.sortOptions.parent = this; // it allows the Methods object to know who its Parent is
delete this.init; // if you don't need the Init method anymore after the you instanced the object you can remove it
return this; // it gives back the object itself to instance it
}
}.init();
}
};
})
Create a custom directive to design paging template as follows,
rapid.directive('footerPager', function () {
return {
restrict: 'E',
transclude: true,
template:
'<div class="col-xs-9 text-right" ng-cloak>\
<span ng-if="options.totalItems > options.itemsPerPage">\
<pagination \
ng-model="options.page" \
total-items="options.totalItems" \
items-per-page="options.itemsPerPage" \
ng-change="options.goToPage(options.page)" \
max-size="5" rotate="false" boundary-links="true" \
previous-text="‹" next-text="›" \
first-text="«" last-text="»" \
class="pagination-sm">\
</pagination>\
</span>\
</div>\,
scope: {
options: '='
}
}
});
In cshtml file use the above created custom directive as follows,
<footer-pager options="pagingOptions" id="footer"/>
In corresponding controller.js file create and set the 'pagerOptions' object by calling the 'newOptions' method of the above created service,
rapid.controller('HomeListController',
['$scope', 'adminSvc','pagerOptions',
function auditLogCtrl($scope,adminSvc,pagerOptions) {
$scope.pagingOptions = pagerOptions.newOptions();
$scope.pagingOptions.sortBy = "CreatedDate";
$scope.pagingOptions.itemsPerPage = 10;
$scope.pagingOptions.onPageChange = loadData; //loadData is a method load the data to the page.
var numberOfSearchPerfomed = 0;
$scope.data= {};
function loadData() {
$scope.pagingOptions.filters = selectedFilters;
service.getData(vm.pagingOptions) //Method will fetch data from db and show in the view based on pagingOptions.
.success(function (result) {
$scope.data= result.Data;
$scope.pagingOptions.totalItems = result.TotalCount; // TotalCount represents the total number of records not page wise.
$scope.enableResetButton = numberOfSearchPerfomed >= 1;
});
}
loadData();
}])

Filter Data Using Knockout JS

I have static array that have 2 set of data.
I have make 2 part of the one div and on right side show all list from array and on left side nothing.
On right side have put + sign on button, on it's click that record came on left side div and working fine and at that time the plus sign become minus when that record came on left side, when click on minus sign again that record removed from left side. Just like toggle.
Now I want to filter the right side of list using textbox.
It will search on 2 columns i.e. code and title.
but how to make filter I don't know.
HTML Code :
<div class="col-md-6">
<div class="col-md-4">
<input type="text" required id="filterD" class="form-control" data-bind=""/>
</div>
<!-- ko foreach: controlFields -->
<div class="row">
<div class="col-md-11 table-bordered">
<div class="form-group" style="padding-top: 3px;">
<div class="col-md-2" data-bind="text:code">
</div>
<div class="col-md-7" data-bind="text:title">
</div>
<div class="col-md-1" data-bind="text:i1">
</div>
<div class="col-md-1" data-bind="text:i2">
</div>
<div>
<!-- ko ifnot : viewFlag -->
<button class="btn-primary btn-xs" data-bind="click: $root.addField">
<i class="glyphicon glyphicon-plus-sign"></i>
</button>
<!-- /ko -->
<!-- ko if : viewFlag -->
<button class="btn-primary btn-xs" data-bind="click: $root.removeField">
<i class="glyphicon glyphicon-minus-sign"></i>
</button>
<!-- /ko -->
</div>
</div>
<!-- ko foreach: subFields -->
<div style="padding-top: 3px" class="form-group" data-bind="attr:{'title':description()}">
<div class="col-md-2">
</div>
<div style="border-top: 1px solid #ddd; " class="col-md-2" data-bind="text:code">
</div>
<div style="border-top: 1px solid #ddd; " class="col-md-7" data-bind="text:title">
</div>
<div>
<button class="btn-primary btn-xs"><i class="glyphicon glyphicon-plus-sign"></i></button>
</div>
</div>
<!-- /ko -->
</div>
</div>
<br />
<!-- /ko -->
</div>
JavaScript :
var exports = {},
ViewModel, ControlField , SubField;
SubField = function(code, title,data,description){
var self = this;
self.code = ko.observable(code);
self.title = ko.observable(title);
self.data = ko.observable(data);
self.description = ko.observable(description);
};
ControlField = function(code, title, i1, i2){
var self = this;
self.code = ko.observable(code);
self.title = ko.observable(title);
self.i1 = ko.observable(i1);
self.i2 = ko.observable(i2);
self.subFields = ko.observableArray([]);
self.viewFlag = ko.observable(false);
};
ViewModel = function(data) {
var self = this;
self.controlFields = ko.observableArray([]);
var controlField = new ControlField("100","BookTitle","0","1");
self.controlFields.push(controlField);
controlField.subFields().push(new SubField("a","Title","JAVA","For Entering Item Title Data"));
controlField.subFields().push(new SubField("p","Section","2","For Section"));
var controlField1 = new ControlField("245","Author","1","0");
self.controlFields.push(controlField1);
controlField1.subFields().push(new SubField("a","Name","Herbert","Name of The Author"));
controlField1.subFields().push(new SubField("d","Place","Ontario","Place of Author"));
self.addField = function(field){
field.viewFlag(true);
};
self.removeField = function(field){
field.viewFlag(false);
};
};
I want that when I type any character in input=text it will filter data and then show.
Any suggestion on this.
Here's Screen of this code :
You can use ko.computed for filtering the data.
//filter html binding
<input type="text" required id="filterD" class="form-control" data-bind="value:filter,valueUpdate: 'keyup'" />// use valueUpdate binding
//bind filter to filter text
self.filter = ko.observable();
//Use filteredList in html binding instead of controlFields
self.filteredList = ko.computed(function () {
var filter = self.filter(),
arr = [];
if (filter) {
ko.utils.arrayForEach(self.controlFields(), function (item) {
if (item.code() == filter || item.title() == filter) {
arr.push(item);
}
});
} else {
arr = self.controlFields();
}
return arr;
});
Fiddle Demo
//sorry for ui part(Html alignment) in demo.

how to generate list dynamically in angular.js

can you please tell me how to create list dynamically in angulat.js..Actullly I am able to make list when user press add button and fill the field .
In other words ,Please check this fiddle whenever you fill the fields it generate a row.And you can get Id when you click the row .Fiddle http://jsfiddle.net/wc4Jm/6/
Now I am trying to do this using bootstrap model .in other words on button click first I show a pop up screen then there is "add" button .on click that it generate the row.but I am getting "undefined".My I insert the model div inside the controller ? here is
http://jsbin.com/vubojoxo/4/
Why I am getting this error ?
XMLHttpRequest cannot load file:///C:/Users/asd/Desktop/angular/angularproject/dialog.html. Received an invalid response. Origin 'null' is therefore not allowed access.
I am getting this error when I used plunker..and run in my desktop ..
I make this html ?
<!doctype html>
<html ng-app="plunker">
<head>
<script src="angular.js"></script>
<script src="ui-bootstrap-tpls-0.2.0.js"></script>
<link href="bootstrap-combined.min.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<div ng-controller="DialogDemoCtrl">
<a class="btn" data-toggle="modal" href="" ng-click="openPopupScreen()">Add Contend</a>
</div>
</body>
</html>
....
Dialog.html
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h1>Add Element</h1>
</div>
<div class="modal-body">
<form >
<label>Name:</label><input type="text" class="span3" ng-model="activeItem.name"></br>
<label>Content Name:</label><input type="password" class="span3" ng-model="activeItem.content"></br>
<button type="submit" class="btn btn-success" ng-click="addItem()">Add In List</button>
<button type="reset" class="btn ">Clear</button>
</form>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal" aria-hidden="true">close</a>
</div>
js code:
var myApp = angular.module('plunker', ['ui.bootstrap']);
myApp.controller('DialogDemoCtrl', function($scope,$dialog) {
$scope.items = [];
$scope.activeItem = {
id:'',
name: '',
content: ''
};
$scope.addItem = function () {
$scope.activeItem.id = $scope.items.length + 1;
$scope.items.push($scope.activeItem);
$scope.activeItem = {}; /* reset active item*/
};
$scope.getId = function (item) {
alert('ID: '+item.id);
};
$scope.openPopupScreen = function () {
alert('Check Open pop up screen');
$dialog.dialog({}).open('dialog.html');
};
});
Check this Plunker
In this example i used angular-ui library which wraps bootstrap's modal to angular
based on this StackOverflow Answer
ModalDemoCtrl
$scope.items = [];
$scope.getId = function(item) {
alert('ID: ' + item.id);
};
// This opens a Bootstrap modal
$scope.open = function() {
var modalInstance = $modal.open({
template: $scope.modal_html_template,
controller: ModalInstanceCtrl
});
modalInstance.result.then(function(newItem) {
// On modal success
newItem.id = $scope.items.length + 1;
$scope.items.push(newItem);
}, function() {
// On modal cancelation
});
}
ModalInstanceCtrl
$scope.name = '';
$scope.content = '';
$scope.ok = function() {
var response = {
'name': $scope.name,
'content': $scope.content
};
$modalInstance.close(response);
};
$scope.cancel = function() {
$modalInstance.dismiss('cancel');
};
HTML
<body>
<div ng-controller="ModalDemoCtrl">
<div inner-html-bind="" inner-html="modal_html_template" class="hidden">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>Name</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.name" placeholder="Enter Name">
</div>
<div class="form-group">
<label>Content</label>
<!-- using $parent because ui-bootstrap nested 2 controllers. this is a workaround -->
<input type="text" class="form-control" ng-model="$parent.content" placeholder="Enter Content">
</div>
</div>
<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>
</div>
<div class="container">
<h2>Modal Example https://stackoverflow.com/questions/24988561</h2>
<button class="btn" ng-click="open()">Open Modal</button>
<div>
<ul>
<li ng-repeat="item in items">
<a ng-click="getId(item)">{{ item.id }} | {{ item.name + ' ' + item.content }}</a>
</li>
</ul>
</div>
</div>
</div>
</body>

Categories

Resources