Display multiple <td> elements on same line with angular-js - javascript

Below code displays data within an ng-repeat . I'm attempting to include a new line after every 5 elements are displayed :
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var json = {
"modules":
[
{
"category":"Sport",
"title":"Sport New Title",
"description" : "Sport This is description",
"fullDescription" : "fullDescription Sport This is description",
"hrefLink" : "http://www.google.com",
"hrefTitle" : "Google",
"dateAdded" : "11-11-11"
},
{
"category":"News",
"title":"Scala New Title",
"description" : "Scala This is description",
"fullDescription" : "fullDescription Sport This is description",
"hrefLink" : "http://www.google.com",
"hrefTitle" : "Google",
"dateAdded" : "11-11-11"
},
{
"category":"Scala",
"title":"Scala New Title",
"description" : "Scala This is description",
"fullDescription" : "fullDescription Sport This is description",
"hrefLink" : "http://www.google.com",
"hrefTitle" : "Google",
"dateAdded" : "11-11-11"
}
]
};
$scope.ocw = json;
});
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css">
<script src="http://code.angularjs.org/1.1.4/angular.js"></script>
<script src="app.js"></script>
</head>
Search: <input ng-model="searchText">
<body ng-controller="MainCtrl">
<table class="table table-bordered" ng-repeat="module in ocw.modules | filter:searchText">
<td>
<h3 class="moduletitle">{{ module.category }} {{$index}}</h3>
<p>{{ module.title }}</p>
<p>{{ module.description }}</p>
<p> {{ module.hrefTitle }}</p>
</td>
<div ng-if={{$index}}" % 5 === 0">
<tr></tr>
</div>
</div>
</table>
</body>
</html>
But problem is <td> elements are wrapped by <tr> . This appears to be generated by ng-repeat. Can these td elements be displayed on one row and separated every 5 elements ?
Plunkr : http://plnkr.co/edit/MnSD7u1pCKV7kTQkGFPT?p=preview

Try this : http://plnkr.co/edit/D7XyPDM8uJzArqcaWtJf?p=preview
First, you divide your actual JSON into rows by using a chunk methods (as seen here )
function chunk(arr, size) {
var newArr = [];
for (var i=0; i<arr.length; i+=size) {
newArr.push(arr.slice(i, i+size));
}
return newArr;
}
json.modules = chunk(json.modules, 5);
Then in your HTML use two ng-repeat. One in the TR for the rows and one in the TD for each element of the row :
<table class="table table-bordered">
<tr ng-repeat="(rowIndex, row)in ocw.modules">
<td ng-repeat="module in row | filter:searchText">
<h3 class="moduletitle">{{ module.category }} {{$index+(rowIndex*5)}}</h3>
<p>{{ module.title }}</p>
<p>{{ module.description }}</p>
<p> {{ module.hrefTitle }}</p>
</td>
</tr>
</table>
The answer by m59 that I have linked also shows how to rejoin your data if you need to use it "unchucked".

Related

How to paginate array of array to Material Design Data Table angularjs?

I have table and i show data, with dynamic columns and data. As input data i have an array of values
here is my plunker
angular.module('plunker', ['ngMaterial','md.data.table'])
.config(['$mdThemingProvider', function ($mdThemingProvider) {
'use strict';
$mdThemingProvider.theme('default')
.primaryPalette('blue');
}])
.controller('MainCtrl', function($scope) {
var vm = $scope;
vm.test = '123';
vm.query = {
order: 'starttime',
limit: 25,
page: 1
};
vm.tabQuery = {
limit: 2,
page: 1
};
vm.data = {
"title": "Summary Reports -> manipulate",
"content": [
[
"a1s2",
"1"
],
[
"aaa",
"1"
],
[
"ccc",
"1"
],
[
"eee",
"1"
],
[
"ggg",
"1"
],
[
"iii",
"1"
],
[
"kkk",
"1"
],
[
"mmm",
"1"
],
[
"ooo",
"1"
],
[
"qqq",
"1"
],
[
"sss",
"1"
]
],
"columns": [
"name1",
"name2"
],
"transactionLogId": 432903
};
$scope.name = 'Plunker';
});
[ng\:cloak],
[ng-cloak],
[data-ng-cloak],
[x-ng-cloak],
.ng-cloak,
.x-ng-cloak {
display: none !important;
}
h1,
p {
font-family: sans-serif;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/daniel-nagy/md-data-table/master/dist/md-data-table.css">
</head>
<body ng-app="plunker" ng-cloak>
<div ng-controller="MainCtrl">
<md-toolbar class="md-table-toolbar md-default">
<div class="md-toolbar-tools" layout-align="end center">
<span class="md-subhead">Summary Report</span>
<div flex></div>
</div>
</md-toolbar>
<md-table-container md-scroll-y layout-fill layout="column" class="md-padding">
<table class="md-table" md-table md-progress="promise" style="font-size: 11px !important;">
<thead md-head>
<tr md-row>
<th md-column ng-repeat="col in data.columns track by $index"> {{ col }}</th>
</tr>
</thead>
<tbody md-body>
<tr md-row ng-repeat="val in data.content track by $index">
<td ng-repeat="el in val track by $index" md-cell ng-bind="el"></td>
</tr>
</tbody>
</table>
</md-table-container>
<md-table-pagination md-limit="3" md-boundary-links="true" md-limit-options="[5, 10, 15]" md-page="tabQuery.page" md-total="{{(data.content).length}}"></md-table-pagination>
</div>
<script src="lib/script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular-animate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular-aria.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.2.2/angular-material.min.js"></script>
<script src="https://rawgit.com/daniel-nagy/md-data-table/master/dist/md-data-table.js"></script>
</body>
</html>
My pagination via array of array doesn't works in this table.
I'm also tried add this part to ng-repeat:
"| limitTo: query.limit : (query.page -1) * query.limit"
The problem is: there is a table in AngularJS, there are, for example, 2 columns (maybe 5 and 10, they are dynamic) and also dynamic data, I bring an array for these columns into the table, for example I took 2 columns and 11 records, brought them into the table and made them the table showed 3 items, but it shows all 11 and pagination does not seem to rob, can anyone pushed with this?
Solved, I've added | limitTo: query.limit : (query.page -1) * query.limit to <td ng-repeat="el in val track by $index" md-cell>{{ el }}</td> and deleted ng-bind="el" (changed to {{ el }}) now it works as expect

I used data tables for list populated in JSP file and in jsp file List is not displayed proper

Hi I am new to jQuery and Bootstrap . I am using Data tables to displayed data in table format but issue is that when one column data is too long I get horizontal scroll bar as shown in below image:
below is my code:
<!DOCTYPE html>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="s" uri="http://www.springframework.org/tags" %>
<html lang="en">
<head>
<jsp:directive.include file="include_metatags.jsp" />
<title><s:message code="app.title.transactionlist" arguments="${applicationScope['APPLICATION_HEADER_TEXT']}"/></title>
<jsp:directive.include file="include_head.jsp" />
<link href="resources/css/datatables.min.css" rel="stylesheet">
<style>
body,html{
background-image : url("resources/img/xyymm/home.jpg");
background-attachment : fixed;
background-position : center center;
background-size : cover;
}
</style>
</head>
<body>
<jsp:include page="menu.jsp">
<jsp:param value="transactions" name="currentpage" />
</jsp:include>
<div class="container amo2">
<div class="card card-container2">
<img id="profile-img" class="profile-img-card" src="resources/img/xyymm/fintech_img.png">
<h4 style="margin-bottom:20px;">
<s:message code="label.list.transaction"/>
</h4>
<div class="container-fluid mer table-responsive" id="wht">
<ol class="breadcrumb">
<li><s:message code="app.link.home"/></li>
<li class="active"><s:message code="form.home.transactionList"/></li>
</ol>
<jsp:directive.include file="alertMessage.jsp" />
<div class="body-content">
<table border="1" id="transactions" class="table table-striped table-responsive dataTable no-footer dtr-inline" role="grid" aria-describedby="transactions_info">
<thead>
<tr>
<td><s:message code="form.transactionlist.transactionId"/></td>
<td><s:message code="form.transactionlist.merchantId"/></td>
<td><s:message code="form.transactionlist.invoiceNumber"/></td>
<td><s:message code="form.transactionlist.amount"/></td>
<td><s:message code="form.transactionlist.currency"/></td>
<td><s:message code="form.transactionlist.paymentGateway"/></td>
<td><s:message code="form.transactionlist.orderStatus"/></td>
<td><s:message code="form.transactionlist.createdDate"/></td>
</tr>
</thead>
<tbody>
<c:forEach var="transaction" items="${transactionList}">
<tr>
<td>
<a href="#transactionView" id="transactionsPopup" data-toggle="modal" data-target=".bs-example-modal-lg"
onclick="viewTransactionDetails('${transaction.transactionId}')">
${transaction.transactionId}
</a>
</td>
<td>${transaction.merchantId}</td>
<td>${transaction.invoiceNum}</td>
<td>${transaction.amount}</td>
<td>${transaction.currency}</td>
<td>${transaction.domainName}</td>
<td>${transaction.orderStatus}</td>
<td>${transaction.createdDate}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
<jsp:include page="transactionListPopup.jsp">
<jsp:param name="divID" value="transactionView" />
</jsp:include>
<jsp:directive.include file="include_body_scripts.jsp" />
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="resources/js/datatables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#transactions').DataTable({
"order": [[7,"asc"]],
responsive: true,
"autoWidth": false,
"columnDefs": [
{
"width" : "10%",
"targets": [ 7 ],
"visible": false
},
{
"width" : "5%",
"targets": [ 1 ],
"visible": false
}
]
}
);
} );
function viewTransactionDetails(transactionId) {
return $.ajax({
url: 'transactions',
type: 'GET',
data: {"transactionId" : transactionId},
dataType: "json",
success: function (item) {
var trMerchantHTML = 'Merchant ID - '+ item.merchantId;
var trEmailHTML = 'Pay From Email - '+ item.payFromEmail;
var trFirstHTML = 'First Name - '+ item.firstName;
var trLastHTML = 'Last Name - '+ item.lastName;
var trRelayHTML = 'Relay URL - '+ item.relayUrl;
var trInvoiceHTML = 'Invoice Number - '+ item.invoiceNum;
var trAmountHTML = 'Amount - '+ item.amount;
var trCustomerHTML = 'Customer ID - '+ item.customerId;
var trIPHTML = 'IP Address - '+ item.ipAddress;
var trCurrencyHTML = 'Currency - '+ item.currency;
var trDomainHTML = 'Domain Name - '+ item.domainName;
var trOrdersHTML = 'Order Status - '+ item.orderStatus;
var trRedirectHTML = 'Is Redirect - '+ item.isredirect;
var trTransMsgHTML = 'Transaction Message - '+ item.txn_message;
var trMerchOrderIdHTML = 'Merchant Order ID - '+ item.merch_order_id;
var trMerchTransIdHTML = 'Merchant Transaction ID - '+ item.merch_txn_id;
var trActionHTML = 'Action - '+ item.action;
$('#merchantID').html(trMerchantHTML);
$('#payFromEmailID').html(trEmailHTML);
$('#firstNameID').html(trFirstHTML);
$('#lastNameID').html(trLastHTML);
$('#relayUrlID').html(trRelayHTML);
$('#invoiceNumberID').html(trInvoiceHTML);
$('#amountID').html(trAmountHTML);
$('#customerID').html(trCustomerHTML);
$('#ipAddressID').html(trIPHTML);
$('#currencyID').html(trCurrencyHTML);
$('#domainNameID').html(trDomainHTML);
$('#orderStatusID').html(trOrdersHTML);
$('#isRedirectID').html(trRedirectHTML);
$('#txnMessage').html(trTransMsgHTML);
$('#merchantOrderID').html(trMerchOrderIdHTML);
$('#merchantTransID').html(trMerchTransIdHTML);
$('#action').html(trActionHTML);
},
error: function() {
$('#transactionView_Table ').html('<p>An error has occurred.</p>');
}
});
}
</script>
</body>
</html>
I don't want Scroll bar Can anybody has idea how to break column values in 2 or more lines means in above image there is MerchantID column and I want to show data in this column in two or more lines.
Is there any property in data tables which decreases width of particular column?
Please anybody can help me to get this? Thanks in advance.
Finally I got answer for my question.
<td>${transaction.merchantId}</td>
added style for break line as given below:
<td style="word-break: break-all;word-break: breakword;width:15%;"> ${transaction.merchantId}</td>
here we can adjust width according to our data consumption. one can add this style in all required columns.

Angularjs Impossible to load multiply ng-apps in one page even with angular.boostrap [duplicate]

I have just started learning Angular JS and created some basic samples however I am stuck with the following problem.
I have created 2 modules and 2 controllers.
shoppingCart -> ShoppingCartController
namesList -> NamesController
There are associated views for each controller. The first View renders fine but second is not rendering. There are no errors.
http://jsfiddle.net/ep2sQ/
Please help me solve this issue.
Also is there any possibility to add console in View to check what values are passed from Controller.
e.g. in the following div can we add console.log and output the controller values
<div ng-app="shoppingCart" ng-controller="ShoppingCartController">
</div>
So basically as mentioned by Cherniv we need to bootstrap the modules to have multiple ng-app within the same page. Many thanks for all the inputs.
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [{
product_name: "Product 1",
price: 50
}, {
product_name: "Product 2",
price: 20
}, {
product_name: "Product 3",
price: 180
}];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [{
username: "Nitin"
}, {
username: "Mukesh"
}];
}
);
angular.bootstrap(document.getElementById("App2"), ['namesList']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div id="App2" ng-app="namesList" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
To run multiple applications in an HTML document you must manually bootstrap them using angular.bootstrap()
HTML
<!-- Automatic Initialization -->
<div ng-app="myFirstModule">
...
</div>
<!-- Need To Manually Bootstrap All Other Modules -->
<div id="module2">
...
</div>
JS
angular.
bootstrap(document.getElementById("module2"), ['mySecondModule']);
The reason for this is that only one AngularJS application can be automatically bootstrapped per HTML document. The first ng-app found in the document will be used to define the root element to auto-bootstrap as an application.
In other words, while it is technically possible to have several applications per page, only one ng-app directive will be automatically instantiated and initialized by the Angular framework.
You can use angular.bootstrap() directly... the problem is you lose the benefits of directives.
First you need to get a reference to the HTML element in order to bootstrap it, which means your code is now coupled to your HTML.
Secondly the association between the two is not as apparent. With ngApp you can clearly see what HTML is associated with what module and you know where to look for that information. But angular.bootstrap() could be invoked from anywhere in your code.
If you are going to do it at all the best way would be by using a directive. Which is what I did. It's called ngModule. Here is what your code would look like using it:
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
<script src="angular.ng-modules.js"></script>
<script>
var moduleA = angular.module("MyModuleA", []);
moduleA.controller("MyControllerA", function($scope) {
$scope.name = "Bob A";
});
var moduleB = angular.module("MyModuleB", []);
moduleB.controller("MyControllerB", function($scope) {
$scope.name = "Steve B";
});
</script>
</head>
<body>
<div ng-modules="MyModuleA, MyModuleB">
<h1>Module A, B</h1>
<div ng-controller="MyControllerA">
{{name}}
</div>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
<div ng-module="MyModuleB">
<h1>Just Module B</h1>
<div ng-controller="MyControllerB">
{{name}}
</div>
</div>
</body>
</html>
You can get the source code for it at:
http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/
It's implemented in the same way as ngApp. It simply calls angular.bootstrap() behind the scenes.
In my case I had to wrap the bootstrapping of my second app in angular.element(document).ready for it to work:
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("app2"), ["app2"]);
});
Here's an example of two applications in one html page and two conrollers in one application :
<div ng-app = "myapp">
<div ng-controller = "C1" id="D1">
<h2>controller 1 in app 1 <span id="titre">{{s1.title}}</span> !</h2>
</div>
<div ng-controller = "C2" id="D2">
<h2>controller 2 in app 1 <span id="titre">{{s2.valeur}}</span> !</h2>
</div>
</div>
<script>
var A1 = angular.module("myapp", [])
A1.controller("C1", function($scope) {
$scope.s1 = {};
$scope.s1.title = "Titre 1";
});
A1.controller("C2", function($scope) {
$scope.s2 = {};
$scope.s2.valeur = "Valeur 2";
});
</script>
<div ng-app="toapp" ng-controller="C1" id="App2">
<br>controller 1 in app 2
<br>First Name: <input type = "text" ng-model = "student.firstName">
<br>Last Name : <input type="text" ng-model="student.lastName">
<br>Hello : {{student.fullName()}}
<br>
</div>
<script>
var A2 = angular.module("toapp", []);
A2.controller("C1", function($scope) {
$scope.student={
firstName:"M",
lastName:"E",
fullName:function(){
var so=$scope.student;
return so.firstName+" "+so.lastName;
}
};
});
angular.bootstrap(document.getElementById("App2"), ['toapp']);
</script>
<style>
#titre{color:red;}
#D1{ background-color:gray; width:50%; height:20%;}
#D2{ background-color:yellow; width:50%; height:20%;}
input{ font-weight: bold; }
</style>
You can merge multiple modules in one rootModule , and assign that module as
ng-app to a superior element ex: body tag.
code ex:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="namesController.js"></script>
<script src="myController.js"></script>
<script>var rootApp = angular.module('rootApp', ['myApp1','myApp2'])</script>
<body ng-app="rootApp">
<div ng-app="myApp1" ng-controller="myCtrl" >
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<div ng-app="myApp2" ng-controller="namesCtrl">
<ul>
<li ng-bind="first">{{first}}
</li>
</ul>
</div>
</body>
</html>
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [{
product_name: "Product 1",
price: 50
}, {
product_name: "Product 2",
price: 20
}, {
product_name: "Product 3",
price: 180
}];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [{
username: "Nitin"
}, {
username: "Mukesh"
}];
}
);
var namesModule = angular.module("namesList2", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [{
username: "Nitin"
}, {
username: "Mukesh"
}];
}
);
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById("App2"), ['namesList']);
angular.bootstrap(document.getElementById("App3"), ['namesList2']);
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div id="App2" ng-app="namesList" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
<div id="App3" ng-app="namesList2" ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="_name in names">
<p>{{_name.username}}</p>
</div>
</div>
</body>
</html>
// root-app
const rootApp = angular.module('root-app', ['app1', 'app2E']);
// app1
const app11aa = angular.module('app1', []);
app11aa.controller('main', function($scope) {
$scope.msg = 'App 1';
});
// app2
const app2 = angular.module('app2E', []);
app2.controller('mainB', function($scope) {
$scope.msg = 'App 2';
});
// bootstrap
angular.bootstrap(document.querySelector('#app1a'), ['app1']);
angular.bootstrap(document.querySelector('#app2b'), ['app2E']);
<!-- angularjs#1.7.0 -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>
<!-- root-app -->
<div ng-app="root-app">
<!-- app1 -->
<div id="app1a">
<div ng-controller="main">
{{msg}}
</div>
</div>
<!-- app2 -->
<div id="app2b">
<div ng-controller="mainB">
{{msg}}
</div>
</div>
</div>
Only one app is automatically initialized. Others have to manually initialized as follows:
Syntax:
angular.bootstrap(element, [modules]);
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8" data-require="angular.js#1.5.8"></script>
<script data-require="ui-router#0.2.18" data-semver="0.2.18" src="//cdn.rawgit.com/angular-ui/ui-router/0.2.18/release/angular-ui-router.js"></script>
<link rel="stylesheet" href="style.css" />
<script>
var parentApp = angular.module('parentApp', [])
.controller('MainParentCtrl', function($scope) {
$scope.name = 'universe';
});
var childApp = angular.module('childApp', ['parentApp'])
.controller('MainChildCtrl', function($scope) {
$scope.name = 'world';
});
angular.element(document).ready(function() {
angular.bootstrap(document.getElementById('childApp'), ['childApp']);
});
</script>
</head>
<body>
<div id="childApp">
<div ng-controller="MainParentCtrl">
Hello {{name}} !
<div>
<div ng-controller="MainChildCtrl">
Hello {{name}} !
</div>
</div>
</div>
</div>
</body>
</html>
AngularJS API
You can define a Root ng-App and in this ng-App you can define multiple nd-Controler. Like this
<!DOCTYPE html>
<html>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController1', function ($scope) {
$scope.student = {
firstName: "MUKESH",
lastName: "Paswan",
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
mainApp.controller('studentController2', function ($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Hindi', marks: 67 }
],
fullName: function () {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>
<body>
<div ng-app = "mainApp">
<div id="dv1" ng-controller = "studentController1">
Enter first name: <input type = "text" ng-model = "student.firstName"><br/><br/> Enter last name: <input type = "text" ng-model = "student.lastName"><br/>
<br/>
You are entering: {{student.fullName()}}
</div>
<div id="dv2" ng-controller = "studentController2">
<table border = "0">
<tr>
<td>Enter first name:</td>
<td><input type = "text" ng-model = "student.firstName"></td>
</tr>
<tr>
<td>Enter last name: </td>
<td>
<input type = "text" ng-model = "student.lastName">
</td>
</tr>
<tr>
<td>Name: </td>
<td>{{student.fullName()}}</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<table>
<tr>
<th>Name</th>.
<th>Marks</th>
</tr>
<tr ng-repeat = "subject in student.subjects">
<td>{{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
I have modified your jsfiddle, can make top most module as rootModule for rest of the modules.
Below Modifications updated on your jsfiddle.
Second Module can injected in RootModule.
In Html second defined ng-app placed inside the Root ng-app.
Updated JsFiddle:
http://jsfiddle.net/ep2sQ/1011/
Use angular.bootstrap(element, [modules], [config]) to manually start up AngularJS application (for more information, see the Bootstrap guide).
See the following example:
// root-app
const rootApp = angular.module('root-app', ['app1', 'app2']);
// app1
const app1 = angular.module('app1', []);
app1.controller('main', function($scope) {
$scope.msg = 'App 1';
});
// app2
const app2 = angular.module('app2', []);
app2.controller('main', function($scope) {
$scope.msg = 'App 2';
});
// bootstrap
angular.bootstrap(document.querySelector('#app1'), ['app1']);
angular.bootstrap(document.querySelector('#app2'), ['app2']);
<!-- angularjs#1.7.0 -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.0/angular.min.js"></script>
<!-- root-app -->
<div ng-app="root-app">
<!-- app1 -->
<div id="app1">
<div ng-controller="main">
{{msg}}
</div>
</div>
<!-- app2 -->
<div id="app2">
<div ng-controller="main">
{{msg}}
</div>
</div>
</div>
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body>
<div ng-app="shoppingCartParentModule" >
<div ng-controller="ShoppingCartController">
<h1>Your order</h1>
<div ng-repeat="item in items">
<span>{{item.product_name}}</span>
<span>{{item.price | currency}}</span>
<button ng-click="remove($index);">Remove</button>
</div>
</div>
<div ng-controller="NamesController">
<h1>List of Names</h1>
<div ng-repeat="name in names">
<p>{{name.username}}</p>
</div>
</div>
</div>
</body>
<script>
var shoppingCartModule = angular.module("shoppingCart", [])
shoppingCartModule.controller("ShoppingCartController",
function($scope) {
$scope.items = [
{product_name: "Product 1", price: 50},
{product_name: "Product 2", price: 20},
{product_name: "Product 3", price: 180}
];
$scope.remove = function(index) {
$scope.items.splice(index, 1);
}
}
);
var namesModule = angular.module("namesList", [])
namesModule.controller("NamesController",
function($scope) {
$scope.names = [
{username: "Nitin"},
{username: "Mukesh"}
];
}
);
angular.module("shoppingCartParentModule",["shoppingCart","namesList"])
</script>
</html>

angularjs tutorial code debug

im learning angularjs thru an Apress book and I've come across some code that doesnt work, ive tried to debug but my console isnt giving me any errors or anything. Maybe some experts can guide me thru whats wrong, thanks.
customFilters.js file
// Creating a custom filter
// arguments for the filter method is unique and a factory function that returns a filter function that does the actaul work
angular.module('customFilters',[]).filter('unique', function() {
return function(data, propertyname) {
if (angular.isArray(data) && angular.isString(propertyname)) {
var results = [];
var keys = {};
for (var i = 0; i < data.length; i++) {
var val = data[i][propertyname];
if (angular.isUndefined(keys[val])) {
keys[val] = true;
results.push(val);
}
}
return results;
} else {
return data;
}
}
});
sportsStore.js file
//declaring a dependency called customFilters that contains a unqiue filter
angular.module('sportsStore',['customFilters']);
// calling the angular.module method passing in sportsStore located in app.html
angular.module('sportsStore').controller('sportsStoreCtrl', function($scope) {
$scope.data = {
products: [
{name: "Product 1", description:"A product", category:"Category #1", price: 100},
{name: "Product 2", description:"A product", category:"Category #1", price: 110},
{name: "Product 3", description:"A product", category:"Category #2", price: 210},
{name: "Product 4", description:"A product", category:"Category #3", price: 202}
]
};
});
my productListControllers.js file
angular.module('sportsStore').controller('productListCtrl', function($scope,$filter){
var selectedCategory = null;
$scope.selectedCategory = function(newCategory) {
selectedCategory = newCategory;
};
$scope.categoryFilterFn = function(product) {
return selectedCategory == null || product.category == selectedCategory;
};
});
app.html file
<!DOCTYPE html>
<!-- We are defining the sportStore module here in the html tag-->
<html ng-app="sportsStore">
<head>
<title>Sports Store</title>
<link href="bootstrap.min.css" rel="stylesheet" />
<link href="bootstrap-theme.min.css" rel="stylesheet" />
</head>
<!-- Applying ng-controller to the body tagg -->
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
<a class="navbar-brand" href="#">Sports Store</a>
</div>
<div class="panel panel-default row" ng-controller="productListCtrl">
<div class="col-xs-3">
<a class="btn btn-block btn-default btn-lg" ng-click="selectCategory()">Home</a>
<!-- generating the navigation elements here -->
<a class="btn btn-block btn-default btn-lg" ng-repeat="item in data.products |orderBy:'category'| unique:'category'" ng-click="selectCategory(item)">{{item}}</a>
</div>
<div class="col-xs-8">
<!-- ng-repeat generates elements for each object in an array -->
<!-- we also create a local variable called item -->
<div class="well" ng-repeat="item in data.products | filter:categoryFilterFn">
<h3>
<strong>{{item.name}}</strong>
<span class="pull-right label label-primary">{{item.price | currency}}</span>
</h3>
<span class="lead">{{item.description}}</span>
</div>
</div>
</div>
<script src="angular.js"></script>
<script src="controllers/sportsStore.js"></script>
<script src="filters/customFilters.js"></script>
<script src="controllers/productListControllers.js"></script>
</body>
</html>
You have a typo in your html file. The function is selectedCategory not selectCategory.
There is a typo, the template says selectCategory and the controller says selectedCategory

Binding a single angular expression out of a json-file

I am pretty new to angularJS, and obviously there are some simple things that i do not yet understand. What i want to do is the following:
I've got a de-DE.json (that e.g. has several language-keys for a planned multi-language site) that looks somewhat like this
{
"index": {
"headline": "The title of that view",
"tabmenu": [
{
"id": "home",
"class": "active in",
"title":"Title No. 1",
"description":"Some description"
},
{
"id": "profile",
"class": "",
"title":"Title No. 2",
"banner":"WallBanner.jpg",
"description":"Some description"
},
{
"id": "messages",
"class": "",
"title":"Title No. 3",
"description":"Some description"
},
{
"id": "settings",
"class": "",
"title":"Title No. 4",
"description":"Some description"
}
]
},
"media": {
...
}
}
Next have a look at my index.html that looks like:
<html ng-app id="ng-app">
<head>
<title>Title of the Site</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css">
</head>
<body ng-controller="languageKey">
<div class="container" ng-model="language.index">
<h1>{{ headline }}</h1>
<div class="row">
<div class="col-lg-12">
<ul class="nav nav-tabs" id="myTab">
<li class="active">Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade {{ lg.class }}" id="{{ lg.id }}" ng-repeat="lg in language.index.tabmenu">
<h3>{{ lg.title }}</h3>
<p>{{ lg.description }}</p>
</div>
</div>
</div>
</div>
</div>
<script src="../assets/jquery/jquery.js"></script>
<script src="../assets/bootstrap/js/bootstrap.min.js"></script>
<script src="../assets/angularjs/angular.min.js"></script>
<script>
$(function () {
$('#myTab a:first').tab('show')
})
function languageKey($scope, $http)
{
$http({method: 'POST', url: 'de-DE.json'}).success(function(data)
{
$scope.language = data; //response Data
});
}
</script>
</body>
</html>
So thanks to some google-knownledge the part with the <div ng-repeat="lg in language.index.tabmenu"> works fine.
But much more common are language-keys that are just used once, without repeating html structure like in the above
<h1>{{ headline }}</h1>
(I've also tried <h1 ng-bind="{headline}"
So is there a leightweight way to just call those expressions?
Obviously it doesn't work if i try ng-model="language.index" in that case.
You just have to set your JSON object in your $scope element inside your controller, and you can use it in the view:
$scope.myJSON = {...};
In HTML
<h1>{{myJSON.index.headline }}</h1>
By the way, if you're implementing a multi-language application take a look at angular-translate.
If this works
<div ng-repeat="lg in language.index.tabmenu">
then as long as you load the parsed JSON object into the $scope the same way, this should output the headline:
<h1>{{ language.index.headline }}</h1>
The docs suggest that ng-model only works with inputs:
ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope

Categories