I am facing difficulty in creating grid view for my table whose data is coming from database as a response in JSON format. Both UI and Javascript code are in same file. I have installed ng-grid using npm package at root path of application.
Index.html
<script src="node_modules/angular-ui-grid/ui.grid.min.js"></script>
<script src="ng-grid-2.0.11.min.js"></script>
<table style="width:50%" class="table table-bordered">
<thead>
<tr>
<th>Select</th>
<th>FR_ID</th>
<th>FR_Client</th>
<th>FR_Source</th>
<th>FR_Destination</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searches">
<td><input type="checkbox" /></td>
<td>{{search.id}}</td>
<td>{{search.client}}</td>
<td>{{search.source}}</td>
<td>{{search.destination}}</td>
</tr>
</tbody>
</table>
<div class="small-12 columns">
<div class="submitButton" id="submitButton" ng-app="searchapp">
<div style="visibility:hidden;">{{y=name}}</div>
<input type="submit" value="Search" ng-click="seachRecords(y)" style="font-size:20px" />
</div>
</div>
</div>
Angular:
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl', function ($scope, $http){
$scope.seachRecords = function (y) {
var httpRequest = $http({
method: 'GET',
url: '/user/search?seachString='+y,
}).then(function (response, status) {
var responsetest = JSON.stringify(response.data);
$scope.searches = response.data;
}, function myError(data, status) {
$scope.searches = data;
});
}
});
</script>
I am able to create below table as shown in the image attached but I am trying to get Grid view and not able to form it, please suggest changes required for this.
JSON data should be usable with grid view as follows
<div data-ng-grid="searches"></div>
NOTE: 'responsetest' variable appears to be unused.
The response could be attached to 'searches' directly. Grid view expects a 'data' property to access searches data.
Angular
$scope.searches = JSON.stringify(response);
Try this?
HTML:
<script src="node_modules/angular-ui-grid/ui.grid.min.js"></script>
<script src="ng-grid-2.0.11.min.js"></script>
<div ng-grid="searches"></div>
<div class="small-12 columns">
<div class="submitButton" id="submitButton" ng-app="searchapp">
<div style="visibility:hidden;">{{y=name}}</div>
<input type="submit" value="Search" ng-click="seachRecords(y)" style="font-size:20px" />
</div>
</div>
JS:
<script>
var app = angular.module('myApp',[]);
app.controller('myCtrl', function ($scope, $http){
$scope.seachRecords = function (y) {
var httpRequest = $http({
method: 'GET',
url: '/user/search?seachString='+y,
}).then(function (response, status) {
var responsetest = JSON.stringify(response.data);
$scope.searches = {
data: response.data
}
});
}
});
</script>
Following ng-grid implementation:
http://angular-ui.github.io/ui-grid/
Related
I am not able to get data from html form to my java rest method as parameter.
Here's my html and angular code:
var app=angular.module("myApp",[]);
app.controller("mycon",function($scope,$http){
console.log("entered here1");
$scope.test={};
$scope.add = function() {
console.log("entered here2");
var json=JSON.stringify($scope.test);
console.log($scope.test);
console.log(json);
$http.get("rest/xyz/role",
{
data:json
}
).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
alert("error");
})
}});
<body ng-app="myApp" ng-controller="mycon">
<center>
<h2> Login Here! </h2>
<hr/>
<form >
<table>
<tr>
<td>Signum Id:</td>
<td><input type="text" ng-model="test.sig"/></td>
</tr>
<tr>
<button class="btn waves-effect waves-light" type="submit" ng-click="add()" name="action"> Submit <i class="material-icons right">send</i>
</tr>
</table>
</form>
</center>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
</body>
Rest code goes here:
#GET
#Path("/role")
#Consumes({ MediaType.APPLICATION_JSON})
//#Consumes("text/plain")
#Produces({ "application/json" })
public String list(String s) {
System.out.print("Entered here ");
System.out.print(s);
return null;
}
I want signum field from form to pass as parameter in rest method.
The output I am getting is null.
Use http.post:
$http.post("rest/xyz/role", {
data:json
} ...
This code runs on a SharePoint Web Part page in a Script Editor web part. It makes an AJAX call to get list items from SharePoint, and then it should be populating the form with those items. However, nothing is happening.
<link data-require="bootstrap-css#*" data-semver="3.0.0" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
<h2>Questionnaire:</h2>
<br />
<div ng-app="App">
<div ng-controller="spListCtrl">
<table width="100%" cellpadding="10" cellspacing="2" class="employee-table">
<tr ng-repeat="control in Controls">
<td>{{control.Title}}</td>
<td>
<input type="radio" name="{{control.Id}}" value="Yes">Yes
<input type="radio" name="{{control.Id}}" value="No">No
</td>
<td>
<textarea id="{{control.Id}}Comment"></textarea>
</td>
</tr>
</table>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular-route.js"></script>
<script>
function getDataWithCaml(listName, caml) {
var endpoint = "https://myteamsite.sharepoint.com/_api/web/lists/GetByTitle('" + listName + "')/GetItems(query=#v1)?#v1={\"ViewXml\":\"'" + caml + "'\"}";
return jQuery.ajax({
url: endpoint,
method: "POST",
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose"
}
});
}
var App = angular.module('App', ['ngRoute'])
.controller('spListCtrl', function ($scope, $http) {
var caml = "<View><Query><Where><Contains><FieldRef Name='Title' /><Value Type='Text'>C-04</Value></Contains></Where></Query></View>";
var jsonData = getDataWithCaml("Controls", caml);
jsonData.success(function (data) {
alert('success');
$scope.Controls = data.d.results;
});
});
</script>
Since you are updating scope outside the context of Angular execution, you need to wrap the assignment in $scope.$apply, such as
$scope.$apply(function() {
$scope.Controls = data.d.results;
});
I have a table and in of it's column I want user when click on button that is inside this column pop up window appear which have checkboxes and after user checked checkbox it will be appear as output in same column which were have a button as well as post these values of selected checkboxes and user name to database (PHP). I'm a beginner and i wish anyone help me.
help.html code :
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
myPopup = '';
function openPopup(url) {
myPopup = window.open(url,'popupWindow','width=640,height=480');
if (!myPopup.opener)
myPopup.opener = self;
}
</SCRIPT>
</script>
</head>
<body>
<table border="1">
<tr>
<th> user name </th>
<th>product selected</th>
</tr>
<tr>
<td> <input type="text"/></td>
<td> <button onclick="openPopup('f.html')">select</button></td>
</body>
</html>
And this my f.html code:
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM NAME="popupForm">
<INPUT TYPE="checkbox" >Cell phone</br>
<INPUT TYPE="checkbox" >TV</br>
<INPUT TYPE="checkbox" >Book</br>
<INPUT TYPE="BUTTON" VALUE="Submit">
</FORM>
</BODY>
With AngularJS you would do it like this:
Get the data from server with an ajax request. In the demo I've used static data to reduce complexity.
Create a ng-repeat to create the table
Add the selected data that is stored in an array into the table cell.
Make the list clickable by adding ng-click that opens a bootstrap modal to the table cell or wrap the selected data in a button.
In the modal create a form with ng-repeat with your selected products. Testing if the current item is clicked can be done with array.indexOf(item) !== -1 that returns true if the item is in the array.
With every click to the checkboxes update the product array.
After OK button click, close modal and post the updated data to the server with an ajax request. (A check if the data have changed would be good.)
You could also do it with-out AngularJS but I think there you would have to do a lot more code to get that behaviour.
(I'm also pretty new to javascript and AngularJS, so the code is not perfect, but it works.)
There are probably somethings that could be improved e.g. work with services to do the ajax requests.
There is one bug in the script:
The cancel click is not working as expected. The data will be changed even with cancel click.
You can fix this by working with a copy of the scope data or restore the original data if cancel is clicked.
DEMO
Please find the demo below (it is not working here because it seems that bootstrap.ui uses cookies that are not allowed at SO) and here at jsFiddle. Check it at jsFiddle. There it works.
var app = angular.module('myApp', ['ui.bootstrap']);
app.controller('mainController', function($scope, $modal, $log) {
$scope.products = ['coffee', 'beer', 'wine', 'tea', 'milk'];
// userData will be later from server with $http.get('/phpscript').success(...)
// just dummy userData here because no backend available
$scope.userData = [
{
name: 'John Doe',
selectedProducts: [
'coffee',
'beer',
'wine']
},
{
name: 'Jane Doe',
selectedProducts: [
'coffee',
'tea']
}
];
$scope.changeProducts = function(userData) {
//$scope.items = ['item1', 'item2', 'item3'];
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
//size: size,
resolve: {
user: function() {
return userData;
},
selectedProducts: function() {
return userData.selectedProducts;
},
products: function () {
//console.log($scope.selectedProducts);
return $scope.products; // get all available products
}
}
});
modalInstance.result.then(function (selectedItems) {
//products = selectedItems;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
});
app.controller('ModalInstanceCtrl', function ($scope, $http, $modalInstance, products, selectedProducts, user) {
//console.log('user', user);
$scope.products = products;
$scope.selected = selectedProducts;
$scope.chkChange = function(item) {
console.log(item);
var index = $scope.selected.indexOf(item);
if (index > -1) {
$scope.selected.splice(index, 1);
}
else {
// not selected --> we have to add it
$scope.selected.push(item);
}
console.log($scope.selected);
};
//console.log(selectedProducts);
$scope.ok = function () {
// prepare everything for sending to sever
// --> probably check here if the data have changed or not (not implemented yet)
console.log('new selection', $scope.selected);
var data = $.param({
json: JSON.stringify({
user: user.name,
products: $scope.selected
})
});
$http.post('/echo/json/', data)
.success(function(data, status) {
console.log('posted the following data:', data);
});
$modalInstance.close();//); $scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
//custom filter to display the selected products.
app.filter('array', function() {
return function(input) {
//console.log(input);
return input.join(', ');
};
});
body {
padding: 5px;
}
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.1.js"></script>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<div ng-app="myApp">
<div ng-controller="mainController">
<script type="text/ng-template" id="myModalContent.html">
<!-- template for modal -->
<div class="modal-header">
<h3 class="modal-title">Choose your products!</h3>
</div>
<div class="modal-body">
<form>
<div class="checkbox" ng-repeat="item in products">
<label>
<input type="checkbox" ng-click="chkChange(item)" ng-checked="selected.indexOf(item) !== -1"/>
{{item}}
</label>
</div>
</form>
</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>
</script>
<table class="table">
<tr>
<th>User name</th>
<th>products selected</th>
</tr>
<tr ng-repeat="user in userData">
<td>{{user.name}}</td>
<td><button ng-click="changeProducts(user)">{{( user.selectedProducts | array ) || 'nothing selected!' }}</button></td>
</tr>
</table>
</div>
</div>
This snippet will pop up the box. And the submit will submit everything. I do not think this is what you want. I am guess there will be more products.
Select opens popup
Submit submits to product.php
function openPopup(){
var pop = document.getElementById('pop').style.display='block';
}
#pop{
font:400 1em Arial,sans-serif;
width:20em;
display:none;
position:absolute;
top:0;left:0;
background:#ff0;
color:#000;
height:8em;
z-index:10;
}
#frm{width:100%;}
<FORM id="frm" action="product.php" method="post"><div>
<div id="pop">
<INPUT TYPE="checkbox" >Cell phone</br>
<INPUT TYPE="checkbox" >TV</br>
<INPUT TYPE="checkbox" >Book</br>
<INPUT TYPE="submit" VALUE="Submit">
</div>
</div>
<table border="1">
<tr><th> user name </th><th>product selected</th></tr>
<tr><td> <input type="text"/></td>
<td> <button type="button" onclick="openPopup()">Select</button></td>
</tr></table>
</form>
This snippet will pop up the box. you could get the check box values with JS but I think it would be better to submit to a PHP script at this point. but only you know this. I am now working on submitting everything to a script.
Select opens popup
Submit closes popup
function openPopup(){
var pop = document.getElementById('pop').style.display='block';
}
function closePopup(){
var pop = document.getElementById('pop').style.display='none';
}
#pop{
font:400 1em Arial,sans-serif;
width:20em;
display:none;
position:absolute;
top:0;left:0;
background:#ff0;
color:#000;
height:8em;
z-index:10;
}
#frm{width:100%;}
<div id="pop">
<FORM id="frm" NAME="popupForm"><div>
<INPUT TYPE="checkbox" >Cell phone</br>
<INPUT TYPE="checkbox" >TV</br>
<INPUT TYPE="checkbox" >Book</br>
<INPUT TYPE="BUTTON" VALUE="Submit"onclick="closePopup()">
</div></FORM>
</div>
<table border="1">
<tr>
<th> user name </th>
<th>product selected</th>
</tr>
<tr>
<td> <input type="text"/></td>
<td> <button onclick="openPopup()">select</button></td>
I have a table, which loops over a scope called $scope.sites.
I'm submitting a form which saves a new site to a DB, and then adds to the site scope.
However, when I update $scope.sites, it doesn't update the table. The table is under the same SiteCtrl controller.
The scope is definitely being appended to, as if I output {{ sites.length }} after the form has posted, its value increases (and the data appears in the DB).
If I add {{ sites.length }} to the same part that the form is included (in the ui-view) it updates, outside of that and it doesn't.
Here's some of the code:
The Javascript
Note, I'm using ui-router for nested states.
myApp.config(function($stateProvider, $urlRouterProvider){
// The default route
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'app/partials/welcome.html',
controller: 'WelcomeCtrl'
})
.state('entity', {
url: '/entity/:id',
params: { id: "" },
templateUrl: 'app/partials/entity/index.html',
controller: 'EntityCtrl'
})
.state('entity.site', {
url: '/site',
templateUrl: 'app/partials/site/index.html',
controller: 'SiteCtrl'
})
.state('entity.site.create', {
url: '/create',
templateUrl: 'app/partials/site/create.html',
controller: 'SiteCtrl'
})
....
myApp.controller('SiteCtrl', ['$scope', '$http', '$stateParams', function($scope, $http, $stateParams) {
$scope.entity_id = $stateParams.id;
$scope.site_uuid = $stateParams.siteuuid;
$scope.sites = {};
$scope.site = {};
$scope.errors = {};
$scope.result = {};
$scope.formData = {};
$http({ method: 'GET', url: 'siteurl' }).
success(function (data, status, headers, config) {
$scope.sites= data.data;
}).
error(function (data, status, headers, config) {
console.log(data.result);
console.log(data.code);
});
$scope.submitForm = function() {
$http.post('submiturl', $scope.formData).success(function(data) {
//Clear the form
$scope.formData = {};
$scope.site = data.data;
$scope.sites.push($scope.site);
}).error(function(data){
$scope.errors = data;
});
}
}]);
The HTML
<div ng-controller="SiteCtrl">
<h1>Sites <a ui-sref="entity.site.create" class="btn"><i class="fa fa-plus"></i> Add New Site</a></h1>
<ui-view></ui-view> <!---- The form is included here by a ui-router state --->
<pre>{{ sites.length }}</pre> <!-- this doesnt update, nor does the table --->
<div class="form-group">
<label for="filter">Filter</label>
<input ng-model="filter" class="form-control">
</div>
<table class="striped">
<thead>
<tr>
<td>Name</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="site in sites | filter:filter">
<td><a ui-sref="entity.site.show({siteuuid:site.uuid})" ui-sref-active="child-active">{{ site.name }}</a></td>
</tr>
</tbody>
</table>
The Form
<h1>Create a New Site at {{ entity.name }} <a ui-sref="entity.site" class="btn">Close</a></h1></h1>
<pre>{{ result }}</pre>
<pre>{{ errors }}</pre>
<pre>{{ site }}</pre>
<pre>{{ sites.length }}</pre> <!---- This updates --->
<form name="createNewSiteForm" method="post" ng-submit="submitForm()">
<div class="form-group">
<label for="name">Site Name</label>
<input type="text" name="name" class="form-control" ng-model="formData.name" autocomplete="off" required />
{{ errors.name }}
</div>
<div class="form-group">
<input type="submit" name="create" value="Save {{ formData.name }}" />
</div>
</form>
The form is included as a nested view in the
If there's anything else you'd like to see let me know and I can post it up.
Update
So the solution was to use:
$scope.parent.sites.push($scope.site);
My question is, do I have to use the parent, when the scope should be inherited due to being in the same Controller?
I'm new to Angular shedding some light on this would be very useful for my learning.
I'm trying to hide an portion of HTML that I've included in my index.html. What happens right now is when I search for a user a table, along with contents, gets rendered on the page. The behavior that I want is when "Clear" is pressed that included HTML table, along with its contents, is removed. Right now the table will only show if the $scope.user has a value and that check is done with ng-if. When I click the "Clear" button I set $scope.user to "false" which I thought would remove the include. I've also tried adding it to the table DOM element but that doesn't work either. What am I not getting? I'm sure it's a fairly simple fix for someone who knows more about Angular.
index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="MainController">
<h1>{{ message }}</h1>
<div>{{ error }}</div>
<form name="searchUser" ng-submit="search(username)">
<input type="search" required placeholder="Username..." ng-model="username" />
<input type="submit" value="Search" />
<button ng-click="clearSearch()">Clear</button>
</form>
<div ng-include="'userDetails.html'" ng-if="user"></div>
</body>
</html>
script.js
(function() {
var app = angular.module("githubViewer", []);
var MainController = function($scope, $http) {
var onUserComplete = function(response) {
$scope.user = response.data;
$http.get($scope.user.repos_url)
.then(onRepos, onError);
};
var onRepos = function(response) {
$scope.repos = response.data;
}
var onError = function(reason) {
$scope.error = "Could not fetch the data";
}
$scope.search = function(username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
}
$scope.clearSearch = function() {
return ($scope.user = false);
}
$scope.message = "Github Viewer";
$scope.repoSortOrder = "+name";
};
app.controller("MainController", ["$scope", "$http", MainController])
}());
userDetail.html
<div>
<h2>{{ user.name }}</h2>
<img ng-src="http://www.gravatar.com/avatar/{{ user.gravatar_id }}" />
<h2>User Repositories</h2>
Order By:
<select ng-model="repoSortOrder">
<option value="+name">Name</option>
<option value="-stargazers_count">Stars</option>
<option value="+language">Language</option>
</select>
<table>
<thead>
<tr>
<th>Repository Name</th>
<th>Stars</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="repo in repos | orderBy:repoSortOrder">
<td>{{ repo.name }}
</td>
<td>{{ repo.stargazers_count | number }}</td>
<td>{{ repo.language }}</td>
</tr>
</tbody>
</table>
</div>
I ended up figuring it out. The problem was that the
<button ng-click="clearSearch()">Clear</button>
was in the <form> so when I clicked the "Clear" button the Search function was being executed again. I noticed this via the Chrome console since I had XHR requests turned on...when I clicked "Clear" another GET was being executed.
I moved the button outside of the <form> and the functionality works as expected.
clearSearch() should be setting the value of $scope.user instead of returning a value:
$scope.clearSearch = function() {
$scope.user = false;
}