selectable table modal popup in angular js - javascript

I am trying to open a modal popup with table. How can I do this? In my app.js, on the click event of row open a modal, I also want to update some field with the selected item value. But i can't update with selected value.
my app.js
var tableApp = angular.module('tableApp', ['ui.bootstrap']);
tableApp.controller('tableController', function ($scope,$rootScope, $filter, $modal) {
$scope.filteredPeople = [];
$scope.currentPage = 1;
$scope.pageSize = 10;
$scope.people = [{ id: "1", name: "joe",disable:true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe" },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true }];
$scope.getPage = function () {
var begin = (($scope.currentPage - 1) * $scope.pageSize);
var end = begin + $scope.pageSize;
$scope.filteredPeople = $filter('filter')($scope.people, {
id: $scope.idFilter,
name: $scope.nameFilter
});
$scope.totalItems = $scope.filteredPeople.length;
$scope.filteredPeople = $scope.filteredPeople.slice(begin, end);
};
$scope.getPage();
$scope.pageChanged = function () {
$scope.getPage();
};
$scope.open = function () {
$scope.id = generateUUID();
};
$scope.dblclick = function (index) {
for (var i = 0; i < $scope.filteredPeople.length; i++) {
$scope.filteredPeople[i].disable = true;
}
return index.disable = false;
}
$scope.rowSelect = function (rowdata) {
alert(rowdata.name);
}
});
tableApp.controller('DetailModalController', [
'$scope', '$modalInstance', 'item',
function ($scope, $modalInstance, item) {
$scope.item = item;
$scope.dismiss = function () {
$modalInstance.dismiss();
};
$scope.close = function () {
$modalInstance.close($scope.item);
};
}]);
tableApp.directive('myModal', function ($log, $compile) {
var parm = [];
return {
restrict: 'E',
templateUrl: 'modalBase.html',
scope: {
modal: '=',
idF:'='
},
link: function (scope, element, attrs) {
debugger;
parm.name = attrs.idf;
}
//controller: function ($scope) {
// debugger;
// console.log($scope);
// $scope.selected = {
// item: $scope.modal.items[0]
// };
// $scope.ok = function () {
// debugger;
// alert(parm.name);
// $scope.modal.instance.close($scope.selected);
// };
// $scope.cancel = function () {
// $scope.modal.instance.dismiss('cancel');
// };
// $scope.modal.instance.result.then(function (selectedItem) {
// $scope.selected = selectedItem;
// }, function () {
// $log.info('Modal dismissed at: ' + new Date());
// });
//}
};
});

As I understand, you use angular.ui. I would suggesst you to use $modal service instead of $modalInstance. Using that you can call your modal instance with $modal.open(). And also you don't need to close it in your controller - place appropriate methods on your modal template and it will work by its services
Template:
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
{{ item }}
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="$close()">OK</button>
<button class="btn btn-warning" type="button" ng-click="$dismiss('cancel')">Cancel</button>
</div>
</script>
Controlelr
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
You can find more info about it in angular.ui documentation for modals

Related

Rendering a table in Angular 1 without ng-repeat

I'm trying to find a better way for rendering a large table in Angular than using ngRepeat.
I tried using one-time {{::binding}}s, but found the initial render time remained unchanged, which wasn't satisfactory.
Back to the drawing board, I'm trying to find a much more performant method for assembling data into a HTML table in the DOM. I've been trying to use angular.element() to assemble all the parts into a whole, but with no luck. Any insights?
var app = angular.module('app', []);
app.directive('myTable', function() {
return {
restrict: 'E',
scope: {
ngModel: "=",
},
require: 'ngModel',
link: function(scope, element, attrs) {
scope.$watch('ngModel', function() {
if (typeof scope.ngModel == 'undefined') {
console.log("ngModel not defined yet");
return;
}
element.html('');
var table = angular.element('<table/>');
var tbody = angular.element('<tbody/>');
scope.ngModel.forEach(function(m) {
var tr = angular.element('<tr/>');
m.fields.forEach(function(f) {
var td = angular.element('<td/>')
td.text(f.value);
td.append(tr);
});
tr.append(tbody);
})
tbody.append(table);
table.append(element);
})
}
}
});
app.controller('AppController', function($scope) {
$scope.data = [{
fields: [{
value: 1,
metadata: ""
}, {
value: 2,
metadata: ""
}, {
value: 3,
metadata: ""
}, {
value: 4,
metadata: ""
}, {
value: 5,
metadata: ""
}, ]
},
{
fields: [{
value: 6,
metadata: ""
}, {
value: 7,
metadata: ""
}, {
value: 8,
metadata: ""
}, {
value: 9,
metadata: ""
}, {
value: 10,
metadata: ""
}, ]
}
]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="app" ng-controller="AppController">
<my-table ng-model="data"></my-table>
</div>
</body>
It is inappropriate to involve the ngModel controller in a directive that has no user input elements. Also isolate scope is unnecessary. Evaluate the table-data attribute in the watch expression.
Also of course, fix the backwards append statements:
app.directive('myTable', function() {
return {
restrict: 'E',
̶s̶c̶o̶p̶e̶:̶ ̶{̶
̶n̶g̶M̶o̶d̶e̶l̶:̶ ̶"̶=̶"̶,̶
̶}̶,̶
̶r̶e̶q̶u̶i̶r̶e̶:̶ ̶'̶n̶g̶M̶o̶d̶e̶l̶'̶,̶
link: function(scope, element, attrs) {
scope.$watch(attrs.tableData ̶'̶n̶g̶M̶o̶d̶e̶l̶'̶, function(data) {
if (data) {
console.log("table-data not defined yet");
return;
}
element.html('');
var table = angular.element('<table/>');
var tbody = angular.element('<tbody/>');
data.forEach(function(m) {
var tr = angular.element('<tr/>');
m.fields.forEach(function(f) {
var td = angular.element('<td/>')
td.text(f.value);
̶t̶d̶.̶a̶p̶p̶e̶n̶d̶(̶t̶r̶)̶;̶ tr.append(td);
});
̶t̶r̶.̶a̶p̶p̶e̶n̶d̶(̶t̶b̶o̶d̶y̶)̶;̶ tbody.append(tr);
})
̶t̶b̶o̶d̶y̶.̶a̶p̶p̶e̶n̶d̶(̶t̶a̶b̶l̶e̶)̶;̶ table.append(tbody);
̶t̶a̶b̶l̶e̶.̶a̶p̶p̶e̶n̶d̶(̶e̶l̶e̶m̶e̶n̶t̶)̶;̶ element.append(table);
})
}
}
});
Usage:
<my-table table-data="data"></my-table>
THE DEMO
var app = angular.module('app', []);
app.directive('myTable', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.$watch(attrs.tableData, function(data) {
console.log(data);
if (!data) {
console.log("tableData not defined yet");
return;
}
element.html('');
var table = angular.element('<table/>');
var tbody = angular.element('<tbody/>');
data.forEach(function(m) {
var tr = angular.element('<tr/>');
m.fields.forEach(function(f) {
var td = angular.element('<td/>')
td.text(f.value);
tr.append(td);
});
tbody.append(tr);
})
table.append(tbody);
element.append(table);
})
}
}
});
app.controller('ctrl', function($scope) {
$scope.data = [{
fields: [{
value: 1,
metadata: ""
}, {
value: 2,
metadata: ""
}, {
value: 3,
metadata: ""
}, {
value: 4,
metadata: ""
}, {
value: 5,
metadata: ""
}, ]
},
{
fields: [{
value: 6,
metadata: ""
}, {
value: 7,
metadata: ""
}, {
value: 8,
metadata: ""
}, {
value: 9,
metadata: ""
}, {
value: 10,
metadata: ""
}, ]
}
]
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<my-table table-data="data"></my-table>
</body>

Convert Jsp response into JSON

I have an issue as i am trying to retrieve data from jsp in angularjs. Is it feasible? If not.. what are other ways to get retrieve data in angular js controller. Can anyone else help me out to get solution. My Code is given below....
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-sanitize.min.js"></script>
<script>
angular.module("myApp", []).controller('testController',['$scope', '$http', '$log', function($scope, $http, $log)
{
var stateNameHindi = "";
var stateLandingPageUrl = "";
$scope.ScopeObject = {
states : [
{ name: "राज्य चुनें", Ename: "select", district: [{Hnname: 'जिला चुनें', DEname: "Select" }] },
{ name: "राजस्थान ", Ename: "Rajasthan", district: [{ Hnname: 'जयपुर' , DEname: "jaipur"}] },
{ name: "छत्तीस गढ़ ", Ename: "Chattisgarh", district: [{ Hnname: 'बिलास पुर', DEname: "Bilaspur"}, { Hnname: 'रायपुर', DEname: "raipur"}] },
{ name: "गुजरात ", Ename: "Gujrat", district: [ { Hnname: 'अहमदाबाद', DEname: "Ahmdabad"}, { Hnname: 'सूरत', DEname: "surat"}, { Hnname: 'वड़ोदरा', DEname: "vadodra"} ] }
],
} ;
$scope.selectAction = function(EngStateName, EngCityName ) {
var state = EngStateName.Ename;
var city = EngCityName.DEname;
$scope.CityData = $http.get('/xyz/CityNews.jsp',
{
params:{state: state, city: city}})
.then(function(response)
{
if (response.status == 200){
alert("mayank");
$scope.CityData = JSON.parse(response);
alert("sing" + $scope.CityData);
$log.info(response);}
}, function myError(response) {
$scope.CityData = response.statusText;
});
};
$scope.StateSelect = function(EngStateName) {
var state = EngStateName.Ename;
$scope.StateData = $http.get('/xyz/CityNews.jsp',
{
params:{state: state}})
.then(function(response)
{
if (response.status == 200){
alert("mayank");
$scope.StateData = JSON.stringify(response);
var data = JSON.parse($scope.CityData)
alert("sing" + data);
$log.info(response);}
}, function myError(response) {
$scope.CityData = response.statusText;
});
};
}]);
</script>
<div ng-app="myApp">
<div ng-controller="testController">
<select name="state" ng-options="c.name for c in ScopeObject.states track by c.Ename" ng-model="ScopeObject.SelectedData" ng-change="StateSelect(ScopeObject.SelectedData)">
<option value=''>राज्य चुनें</option>
</select>
<select district="cityname" ng-options="d.Hnname for d in ScopeObject.SelectedData.district track by d.DEname" ng-model="ScopeObject.cityname" ng-change="selectAction(ScopeObject.SelectedData, ScopeObject.cityname )">
<option value=''>जिला चुनें</option>
</select>
<p> {{CityData}} </p>
<p> {{StateData}} </p>
</div>
</div>

Uncaught ReferenceError: $scope is not defined

Receiving the error when the page is loaded. I'm trying to append a new object to an array of entries.
What is wrong with the code?
index.html
Raffler
<div ng-controller="RaffleCtrl">
<form ng-sumbit="addEntry">
<input type="text" ng-model="newEntry.name">
<input type="submit" value="Add">
</form>
<ul>
<li ng-repeat="entry in entries">{{entry.name}}</li>
</ul>
</div>
raffle.js
angular.module('myApp', []).controller("RaffleCtrl", function ($scope) {
$scope.entries = [
{
name: "Larry"
}, {
name: "Curly"
}, {
name: "Moe"
}
]
});
$scope.addEntry = function () {
$scope.entries($scope.newEntry)
$scope.newEntry = {}
};
You wrongly used $scope outside the controller. Use the $scope inside the controller
angular.module('myApp', []).controller("RaffleCtrl", function ($scope) {
$scope.entries = [
{
name: "Larry"
}, {
name: "Curly"
}, {
name: "Moe"
}
];
$scope.addEntry = function () {
$scope.entries($scope.newEntry)
$scope.newEntry = {}
};
});
if you really want to keep it outside
angular.module('myApp', []).controller("RaffleCtrl", function ($scope) {
$scope.entries = [
{
name: "Larry"
}, {
name: "Curly"
}, {
name: "Moe"
}
];
$scope.addEntry = addEntry;
});
function addEntry() {
$scope.entries($scope.newEntry)
$scope.newEntry = {}
};

Angularjs: call a controller method with param from a directive dropdown on change event

I have made a dropdown directive. On selecting a value from the dropdown, a method from the controller is called with the selected filter passed. Everything works fine except that the method is always returning the default selected value, no matter, what is selected.
html:
<div ng-controller="Ctrl">
<div>
<dropdown filters="filters" filter="filter" select="selectFilter(filter)"></dropdown>
</div>
</div>
javascript:
var app = angular.module('app', []);
function Ctrl($scope){
$scope.filters = [
{ Id: 1, Name: "All" }, { Id: 2, Name: "filter1" }, { Id: 3, Name: "filter2" }, { Id: 4, Name: "filter3"}
];
$scope.filter = $scope.filters[0];
$scope.selectFilter = function(selectedFilter){
alert(selectedFilter.Name);
};
}
app.directive('dropdown', function(){
return {
restrict: "E",
scope: {
filter: "=",
filters: "=",
select: "&"
},
template: "<select ng-model=\"filter\" ng-change=\"select(filter)\" ng-options=\"f.Name for f in filters\"></select>"
};
});
Working fiddle: http://jsfiddle.net/wXV6Z/98/
You're using wrong syntax to call method binding.
Try:
ng-change=\"select({filter:filter})\
DEMO
I made this, but the other answer seems better :P
http://jsfiddle.net/wXV6Z/101/
var app = angular.module('app', []);
function Ctrl($scope, $element){
$scope.filters = [
{ Id: 1, Name: "All" }, { Id: 2, Name: "filter1" }, { Id: 3, Name: "filter2" }, { Id: 4, Name: "filter3"}
];
$scope.filter = $scope.filters[0];
}
app.directive('dropdown', function(){
return {
restrict: "E",
scope: {
filter: "=",
filters: "=",
},
template: "<select ng-model=\"filter\" ng-change=\"selectFilter(filter)\" ng-options=\"f.Name for f in filters\"></select>",
controller: function($scope, $element) {
$scope.selectFilter = function(selectedFilter) {
alert(selectedFilter.Name);
}
}
}
});

Select an item in a list on click with knockout

I'm trying to chenge the css class of a li tag when I click on it.
I have this:
Model:
var businessUnitsModel = {
businessUnitsList: ko.observableArray([
{ siteID: "a", title: "business1" },
{ siteID: "b", title: "business2" },
{ siteID: "c", title: "business3" },
{ siteID: "d", title: "business4" }]),
currentSelected: ko.observable(),
selectItem: function (site) { this.currentSelected(site.siteID); }
}
//overall viewModel
var viewModel = {
businessUnits: businessUnitsModel,
};
HTML
<ul class="modal-list" data-bind="'foreach': businessUnits.businessUnitsList">
<li class="filterItem" data-bind="'text': title,
css: { 'filterItemSelect': siteID === $parent.currentSelected },
'click': $parent.selectItem">
</li>
</ul>
CSS
.filterItemSelect {
color:#0069ab;
}
and I can't understand why it is not working.
This is what you are looking for :
JS:
var businessUnitsModel = {
businessUnitsList: ko.observableArray([{
siteID: "a",
title: "business1"
}, {
siteID: "b",
title: "business2"
}, {
siteID: "c",
title: "business3"
}, {
siteID: "d",
title: "business4"
}]),
currentSelected: ko.observable(),
selectItem: function (that, site) {
that.currentSelected(site.siteID);
}
}
//overall viewModel
var viewModel = {
businessUnits: businessUnitsModel,
};
ko.applyBindings(viewModel);
View :
<div data-bind="with :businessUnits">
<ul class="modal-list" data-bind="'foreach': businessUnitsList">
<li class="filterItem" data-bind="'text': title,
css: { 'filterItemSelect': siteID === $parent.currentSelected() },
'click': function(){$parent.selectItem($parent, $data);}"></li>
</ul>
</div>
See fiddle
I hope it helps.
You should use currentSelected function value (i.e. add parentheses) when applying css:
<ul class="modal-list" data-bind="foreach: businessUnitsList">
<li class="filterItem" data-bind="text: title,
css: { 'filterItemSelect': siteID === $parent.currentSelected() },
click: $parent.selectItem">
</li>
</ul>
And script:
var businessUnitsModel = function() {
var self = this;
self.businessUnitsList = ko.observableArray([
{ siteID: "a", title: "business1" },
{ siteID: "b", title: "business2" },
{ siteID: "c", title: "business3" },
{ siteID: "d", title: "business4" }]);
self.currentSelected = ko.observable();
self.selectItem = function (site) {
self.currentSelected(site.siteID);
}
}
ko.applyBindings(new businessUnitsModel());
Fiddle
UPDATE here is update of your markup and view model. You should provide full path to currentSelected() property:
<ul class="modal-list" data-bind="'foreach': businessUnits.businessUnitsList">
<li class="filterItem" data-bind="'text': title,
css: { 'filterItemSelect':
siteID === $parent.businessUnits.currentSelected() },
'click': $parent.businessUnits.selectItem">
</li>
</ul>
And here is fixed problem with model - inside selectItem function this was equal to item which you clicked. Thus you don't want to use self alias to model, you need to specify its name:
var businessUnitsModel = {
businessUnitsList: ko.observableArray([
{ siteID: "a", title: "business1" },
{ siteID: "b", title: "business2" },
{ siteID: "c", title: "business3" },
{ siteID: "d", title: "business4" }]),
currentSelected: ko.observable(),
selectItem: function (site) {
businessUnitsModel.currentSelected(site.siteID);
}
}
//overall viewModel
var viewModel = {
businessUnits: businessUnitsModel,
};
ko.applyBindings(viewModel);
Fiddle

Categories

Resources