Spring: convert from JSTL(forEach) to angular.js(ng-repeat) - javascript

I am new to angular.js, I have a spring MVC application and I will like to switch from jstl to angular.js, I started this way
<table>
<c:forEach var="list" items="${list}">
<tr class="alt" ><td >${list.name}</td><td >${list.value}</td> </tr>
</c:forEach>
</table>
to
<table ng-app="" id="users">
<tr ng-repeat="x in list">
<td>{{ x.name }}</td>
<td>{{ x.value }}</td>
</tr>
</table>

If you really want to write the information directly in HTML you can add a tag with the required script.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
angular.module('AppNameHere', [])
.controller('exampleController', function() {
this.list = [{
name: 'Fool',
value: '12'
},
{
name: 'Bar',
value: '15'
}];
});
</script>
</head>
<body ng-app="AppNameHere">
<table id="users" ng-controller="exampleController as example">
<tr ng-repeat="x in example.list">
<td>{{ x.name }}</td>
<td>{{ x.value }}</td>
</tr>
</table>
</body>
</html>
But, as #Vaelyr said, AngularJS is commonly used to fetch data from server (using ajax or something similar) and show the results on the page:
// By default, you can use only 1 module per page.
angular.module('AppNameHere', [])
// service to load the data from server
.factory('exampleFactory', function($q){
var deferred = $q.defer();
// TODO: Load async...
var list =
[{
name: 'Fool',
value: '12'
},
{
name: 'Bar',
value: '15'
}];
deferred.resolve(list);
return deferred.promise;
})
// controller to show the data on the page
.controller('exampleController', function(exampleFactory) {
var controller = this;
controller.list = [];
// When the data is fetched from the server...
exampleFactory.then(function(list) {
// bind to the page
controller.list = list;
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-app="AppNameHere">
<table id="users" ng-controller="exampleController as example">
<tr ng-repeat="x in example.list">
<td>{{ x.name }}</td>
<td>{{ x.value }}</td>
</tr>
</table>
</body>
</html>

Related

After redirecting to another page how to use controller and scope data of previous page in angularjs

This is for an assignment. Here table contains book details which contains book name, author, price, ISBN and category. When user click on book name it should redirect to order page displaying book name, author and price.
BookPage.html
<script type="text/javascript" src="book.js">
<body ng-app="mymodule" >
<div ng-controller="myController" >
<table border=2>
<thead>
<tr>
<th>ISBN</th>
<th>NAME</th>
<th>AUTHOR</th>
<th>CATEGORY</th>
<th>PRICE</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{ book.ISBN }}</td>
<td >{{ book.Name }}</td>
<td>{{ book.Author }}</td>
<td>{{ book.Category }}</td>
<td>{{ book.price }}</td>
</tr>
</tbody>
</table>
**books.js**
var myapp = angular.module('mymodule', []);
myapp.controller("myController", function($scope, $http,$window) {
$http.get("https://api.myjson.com/bins/p4ujn").then(function(response) {
$scope.books = response.data;
$scope.getdetail=function(){
$scope.getbookdetail=this.book;
$window.location.href = "orderpage.html";
}
});
});
Page to be redirected when user click on book name.
orderpage.html
<script type="text/javascript" src="book.js"></script>
<body ng-app="mymodule" >
<div ng-controller="myController" >
{{getbookdetail.Name}}<br>
{{getbookdetail.Author}}
{{getbookdetail.price }}<br>
</div>
</body
This is my code. It display nothing, just a blank page.
You can use a Service or factory to share the data across the controllers.
DEMO
var app = angular.module("clientApp", [])
app.controller("TestCtrl",
function($scope,names) {
$scope.names =[];
$scope.save= function(){
names.add($scope.name);
}
$scope.getnames = function(){
$scope.names = names.get();
}
}
);
app.factory('names', function(){
var names = {};
names.list = [];
names.add = function(message){
names.list.push({message});
};
names.get = function(){
return names.list;
};
return names;
});
<!doctype html>
<html >
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="clientApp">
<div ng-controller="TestCtrl">
<input type="text" ng-model="name">
<button ng-click="save()" > save</button>
</div>
<div ng-init="getnames()" ng-controller="TestCtrl">
<div ng-repeat="name in names">
{{name}}
</div>
</div>
</body>
</html>
Apart from service/factory , you can go for other options like localStorage and rootScope, but those are not recommended ways.
You should use factory/Services, localStorage, routeParams or Child Parent controllers

What's the meaning of sortBy in ng-click?

I'm pretty new in AgularJS, and when I tried to do the practice:
JS file:
function CustomersController() {
this.sortBy = 'name';
this.reverse = false;
this.customers= [{joined: '2000-12-02', name:'John', city:'Chandler', orderTotal: 9.9956}, {joined: '1965-01-25',name:'Zed', city:'Las Vegas', orderTotal: 19.99},{joined: '1944-06-15',name:'Tina', city:'New York', orderTotal:44.99}, {joined: '1995-03-28',name:'Dave', city:'Seattle', orderTotal:101.50}];
this.doSort = function(propName) {
this.sortBy = propName;
this.reverse = !this.reverse;
};
}
HTML file:
<!doctype html>
<html ng-app="customersApp">
<head>
<title>Iterating Over Data</title>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body ng-controller="CustomersController">
<h2>Customers</h2>
Filter: <input type="text" ng-model="customerFilter.name" />
<br /><br />
<table>
<tr>
<th ng-click="doSort('name')">Name</th>
<th ng-click="doSort('city')">City</th>
<th ng-click="doSort('orderTotal')">Order Total</th>
<th ng-click="doSort('joined')">Joined</th>
</tr>
<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
<td>{{ cust.name }}</td>
<td>{{ cust.city }}</td>
<td>{{ cust.orderTotal | currency }}</td>
<td>{{ cust.joined | date }}</td>
</tr>
</table>
<br />
<span>Total customers: {{ customers.length }}</span>
<script src="angular.js"></script>
<script src="app/app.js"></script>
<script src="app/controllers/customersController.js"></script>
</body>
</html>
On the webpage I can click the table's head and sort by name. So I want to know that what's the meaning of sortBy ? Is it a built-in variable in $scope? I tried to change its name (like "sortby") and it doesn't sort (just reverse). If it is, where could I find the built-in functions of $scope? Thanks a lot!
First of all sortBy is just the name of the variable and is not built into the $scope. You could use anything. Notice that sortBy is referenced in 2 places:
In the HTML:
<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
And in your controller in 2 places:
// This initializes the sort order
this.sortBy = 'name';
// This sets the new sort order when a user clicks on the table heding
this.sortBy = propName;
You are free to use another name for sortBy, you just need to replace it in all of those places.
However, orderBy is specific to the ng-repeat, so you can't change that name. For more information you can check out the last example on this page:
https://docs.angularjs.org/api/ng/directive/ngRepeat

Is it possible to to make many $scope variables in angular

I want to receive from server some JSON data and print it like this:
<div ng-app="myApp" ng-controller="pastController">
<table>
<tr ng-repeat="x in names">
<td>{{ x.shops }}</td>
</tr>
</table>
<table>
<tr ng-repeat="y in names1">
<td>{{ y.shops }}</td>
</tr>
</table>
</div>
<table>
<tr ng-repeat="z in names2">
<td>{{ z.shops }}</td>
</tr>
</table>
and my angular script:
app.controller('pastController', function($scope, $http){
var req = {
method: 'post',
url: 'showData'
};
$http(req).then(function(response){
console.log(response.data.pastData);
$scope.names = response.data.pastData;
$scope.names2 = response.data.presentData;
$scope.names1 = response.data.futureData;
});
});
and here is like my json response looks like:
{
"pastData" :
[
{"id":1, "shopPlace":"warsaw", "shopDate":"2016-08-10", "shops":"milk"},
{"id":2, "shopPlace":"warsaw", "shopDate":"2016-09-10", "shops":"table"}
],
"futureData" :
[
{"id":3, "shopPlace":"krakow", "shopDate":"2016-12-10", "shops":"bread"},
{"id":4, "shopPlace":"kielce", "shopDate":"2016-11-20", "shops":"water"}
],
"presentData" :
[
{"id":5, "shopPlace":"wroclaw", "shopDate":"2016-11-07", "shops":"sugar"}
]
}
Everything works fine for names and only for names for names1 it shows : {{ y.shops }} and for names2: {{ z.shops }}
One problem that I see immediately is that the markup for your 3rd table is outside of the div where the angular application and controller have scope, it should be inside. However, if your second table is not being displayed either, then there must be another issue. Here is a working plunker demonstrating everything working. Note that the data is hardcoded instead of being fetched from an API:
https://plnkr.co/edit/ZbJeatH1SkkVDxqNkQ0b?p=preview
<div ng-app="myApp" ng-controller="pastController">
<table>
<tr ng-repeat="x in names">
<td>{{ x.shops }}</td>
</tr>
</table>
<hr/>
<table>
<tr ng-repeat="y in names1">
<td>{{ y.shops }}</td>
</tr>
</table>
<hr/>
<table>
<tr ng-repeat="z in names2">
<td>{{ z.shops }}</td>
</tr>
</table>
</div>
var app = angular.module('myApp', []);
app.controller('pastController', function($scope, $http) {
var data = {
"pastData" : [{"id":1, "shopPlace":"warsaw", "shopDate":"2016-08-10", "shops":"milk"}, {"id":2, "shopPlace":"warsaw", "shopDate":"2016-09-10", "shops":"table"}],
"futureData" : [{"id":3, "shopPlace":"krakow", "shopDate":"2016-12-10", "shops":"bread"}, {"id":4, "shopPlace":"kielce", "shopDate":"2016-11-20", "shops":"water"}],
"presentData" : [{"id":5, "shopPlace":"wroclaw", "shopDate":"2016-11-07", "shops":"sugar"}]
};
$scope.names = data.pastData;
$scope.names2 = data.presentData;
$scope.names1 = data.futureData;
});
Your html markup is incorrect. Your last table is outside the scope of your controller. This is very easy to see when the markup is properly formatted.
<div ng-app="myApp" ng-controller="pastController">
<table>
<tr ng-repeat="x in names">
<td>{{ x.shops }}</td>
</tr>
</table>
<table>
<tr ng-repeat="y in names1">
<td>{{ y.shops }}</td>
</tr>
</table>
</div>
<table>
<tr ng-repeat="z in names2">
<td>{{ z.shops }}</td>
</tr>
</table>

ng-repeat not working properly

Hello guys so i was running this simple HTML,Angular code and i can not get the movies title and url display in my html....but the $scope.test is displayinmg....HELP!!
angular.module('clientApp')
.controller('MoviesCtrl', function ($scope) {
$scope.test = "tester";
$scope.movies = [
{
title:"Green Card",
url:"https://www.youtube.com/watch?v=_i8C9gO91ts"
},
{
title: "Fidelawit ፊደላዊት",
url: "https://www.youtube.com/watch?v=B4u4A7CF3N0"
},
{
title: "Heran ሔራን",
url: "https://www.youtube.com/watch?v=_TlRGhOdLJ0"
},
{
title: "Lela Mafia ሌላ ማፊያ",
url: "https://www.youtube.com/watch?v=_i8C9gO91ts"
}
];
});
<table class="table table-striped">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>
Add the AngularJS and if it is the first place where you have worked with module, you need define it with empty brackets angular.module('clientApp', [])
angular.module('clientApp', [])
.controller('MoviesCtrl', function ($scope) {
$scope.test = "tester";
$scope.movies = [
{
title:"Green Card",
url:"https://www.youtube.com/watch?v=_i8C9gO91ts"
},
{
title: "Fidelawit ፊደላዊት",
url: "https://www.youtube.com/watch?v=B4u4A7CF3N0"
},
{
title: "Heran ሔራን",
url: "https://www.youtube.com/watch?v=_TlRGhOdLJ0"
},
{
title: "Lela Mafia ሌላ ማፊያ",
url: "https://www.youtube.com/watch?v=_i8C9gO91ts"
}
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='clientApp' ng-controller='MoviesCtrl'>
<table class="table table-striped">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="(key, movie) in movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>
</div>
You probably forgot to load angular.js.
So just add this file on above of all the script files.
<script src="angular.min.js"></script>
You can download this file from here.. https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js
And update angular.module('clientApp') to angular.module('clientApp', [])
Hence the modified code will look like this...
Controller file (.js)
angular.module('clientApp', [])
.controller('MoviesCtrl', function ($scope) {
$scope.test = "tester";
$scope.movies = [
{
title:"Green Card",
url:"https://www.youtube.com/watch?v=_i8C9gO91ts"
},
{
title: "Fidelawit ፊደላዊት",
url: "https://www.youtube.com/watch?v=B4u4A7CF3N0"
},
{
title: "Heran ሔራን",
url: "https://www.youtube.com/watch?v=_TlRGhOdLJ0"
},
{
title: "Lela Mafia ሌላ ማፊያ",
url: "https://www.youtube.com/watch?v=_i8C9gO91ts"
}
];
});
Html file
<script src="angular.min.js"></script>
<div ng-app='clientApp' ng-controller='MoviesCtrl'>
<table class="table table-striped">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="(key, movie) in movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>
</div>
The problem does not seems too big. Only two things I have done
Added to body to initialise the angular app. B
<body ng-app='clientApp'>
Added ng-controller to table tag
<table class="table table-striped" ng-controller="MoviesCtrl">
However this is must. Must make an [] for zero dependencies.
angular.module('clientApp', [])
Here it goes
angular.module('clientApp', [])
.controller('MoviesCtrl', function ($scope) {
$scope.test = "tester";
$scope.movies = [
{
title:"Green Card",
url:"https://www.youtube.com/watch?v=_i8C9gO91ts"
},
{
title: "Fidelawit ፊደላዊት",
url: "https://www.youtube.com/watch?v=B4u4A7CF3N0"
},
{
title: "Heran ሔራን",
url: "https://www.youtube.com/watch?v=_TlRGhOdLJ0"
},
{
title: "Lela Mafia ሌላ ማፊያ",
url: "https://www.youtube.com/watch?v=_i8C9gO91ts"
}
];
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
</head>
<body ng-app='clientApp'>
<table class="table table-striped" ng-controller="MoviesCtrl">
<thead>
<th>Title</th>
<th>URL</th>
</thead>
<tbody>
<tr ng-repeat="movie in movies">
<td>{{ movie.title }}</td>
<td>{{ movie.url }}</td>
</tr>
</tbody>
</table>
</body>
</html>

pass dom object to processing function in angularjs

In the following code, I am trying to pass the table cell (as a DOM object) to the function, but this doesn't mean the DOM object for the table cell, it appears that it refers to the $scope. Any idea how to do this?
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr >
<td ng-click="dum();">ONE</td>
<td>TWO</td>
</tr>
<tr ng-repeat="x in names">
<td ng-click="dum(this);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
obj1 = "haha";
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function (response) {$scope.names = response.records;});
$scope.dum = function(x) { obj1 = x; console.log(x); }
});
</script>
</body>
</html>
In angular, you should always code against your data. Coding against the DOM is unnecessary in all but the most extreme edge cases, and when it is necessary, it's usually best done in a directive, where you can control how the rest of the angular app is updated.
In your case, you don't need to access the DOM, or the element, or even an event. You already have all the information you need in order to handle your code with the data.
<tr ng-repeat="x in names">
<td ng-click="dum(x);">{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
and in the controller:
$scope.dum = function(x) { console.log(x); }
You could, probably, do this:
In your HTML
<td ng-click="dum($event);">{{ x.Name }}</td>
In your Javascript
$scope.dum = function(e) { obj1 = e.target; console.log(x); }
//e.target will be the clicked element.
I would not recommend accessing the DOM from a controller, but you can use the $event.target. Here's a plunker example: http://plnkr.co/edit/wFdnPJVa7BHOcvkPqNNT?p=preview
angular.module('Test', [])
.controller('testCtrl', ['$scope', function($scope)
{
$scope.myFunc = function(e)
{
console.dir(e.target);
}
}]);
And the HTML
<body ng-app="Test">
<div ng-controller="testCtrl">
<button ng-click="myFunc($event)">Click Me</button>
</div>
</body>

Categories

Resources