Hi I want same controller in different pages. How to pass the object to different pages. Below is my sample code.
Page1.html
<body ng-app="myapp" ng-controller="studentController">
<div>
<table border="0">
<tr>
<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 ng-view></div>
</body>
Script.js
var app = angular.module("myapp", ["ngRoute"]);
app.config(function ($routeProvider) {
$routeProvider
.when("/Page1", {
template: '<h1>Page 1</h1>'
})
.when("/Page2", {
templateUrl: 'Page2.html',
controller: 'studentController'
})
.otherwise({
template: '<h1>note found</h1>'
})
});
app.controller('studentController', function ($scope) {
$scope.student = {
firstName: "AAA",
lastName: "ZZZ",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Computers', marks: 67 }
],
};
});
Page2.html
<body ng-app="myapp" ng-controller="studentController">
<h1>Hello</h1>
<h2>
subject name - {{ subject.name }}
</h2>
</body>
How to pass subject object from page 1 to page 2.
I define same controller in route config.
Is there anything do i need to define?
You can use a service for that. A service is a singleton in AngularJs, so there is only one instance of it, which makes it a perfect fit if you wanna share data over different controllers
app.service('studentService', function() {
this.student = {
firstName: "AAA",
lastName: "ZZZ",
fees: 500,
subjects: [
{ name: 'Physics', marks: 70 },
{ name: 'Chemistry', marks: 80 },
{ name: 'Math', marks: 65 },
{ name: 'English', marks: 75 },
{ name: 'Computers', marks: 67 }
],
};
this.getSubjects = function () {
return this.student.subjects;
};
});
You can then inject it in your controller(s):
app.controller('studentController', function ($scope, studentService) {
$scope.subjects = studentService.getSubjects();
});
How to pass subject object from page 1 to page 2.
Instead of passing the object, pass an index.
Use an index in the URL in the ng-repeat:
<tr ng-repeat="subject in student.subjects">
<td> {{ subject.name }}</td>
<td>{{ subject.marks }}</td>
</tr>
Define the route with an index parameter:
.when("/Page2/:index", {
templateUrl: 'Page2.html',
controller: 'subjectController'
})
Subject controller
.controller('SubjectController', function($scope, $routeParams) {
$scope.params = $routeParams;
$scope.subject = $scope.subjects[$routeParams.index];
})
Page2.html
<div>
<h1>Subject index {{params.index}}</h1>
<h2>
subject name - {{ subject.name }}
</h2>
</div>
The controller in the ng-view element will inherit the data from the controller instantioated in the main app.
Related
How do I stop default sorting inside the ng-repeat for dynamic table data ?
Currently I am getting below order:
Addr | CustomerId | Name
but what I want is below ordering:
CustomerId | Name | Addr
Any Help would me much appreciated.
JS:
app.controller('MyController', function ($scope) {
$scope.Customers = [
{ CustomerId: 1, Name: "John Hammond", Addr:'India'
},
{
CustomerId: 2, Name: "Mudassar Khan", Addr:'India'
},
{
CustomerId: 3, Name: "Suzanne Mathews", Addr:'India'
},
{
CustomerId: 4, Name: "Robert Schidner", Addr: 'India'
}
];
});
HTML:
<table>
<tr >
<th ng-repeat="(key,value) in Customers[0]">{{key}}</th>
</tr>
<tbody ng-repeat="c in Customers">
<tr>
</tr>
</tbody>
</table>
Try this below way. I hope this below snippet result is showing what you want.
angular.module("aaa",[]).controller('MyController', function ($scope) {
$scope.Customers = [
{ CustomerId: 1, Name: "John Hammond", Addr:'India'
},
{
CustomerId: 2, Name: "Mudassar Khan", Addr:'India'
},
{
CustomerId: 3, Name: "Suzanne Mathews", Addr:'India'
},
{
CustomerId: 4, Name: "Robert Schidner", Addr: 'India'
}
];
$scope.keys = Object.keys($scope.Customers[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="aaa" ng-controller="MyController">
<table>
<tr>
<th ng-repeat="key in keys">
{{key}}
</th>
</tr>
<tbody ng-repeat="c in Customers">
<tr>
<td ng-repeat="key in keys">{{c[key]}}</td>
</tr>
</tbody>
</table>
</div>
So objects in JS are inherently unordered. What you can do is just hard code the keys in the header if that will be fixed for that particular table and then print the values in the respective order.
Something like this:
<table>
<tr >
<th>CustomerId</th>
<th>Name</th>
<th>Addr</th>
</tr>
<tbody>
<tr ng-repeat="c in Customers">
<td>{{CustomerId}}</td>
<td>{{Name}}</td>
<td>{{c.Addr}}</td>
</tr>
</tbody>
</table>
Note: I put the ng-repeat on the tr which is probably what you need. I dont think you should put it on the tbody.
Do you mean the sort order of the data or the display order of the columns?
The accepted answer displays the data by the order of the columns as specified, but if you want the data itself sorted then just add a filter to the data like this:
<tbody ng-repeat="c in Customers|orderBy:['CustomerId','Name','Addr']">
This sorts the actual data in the list by the fields specified.
I am new to AngularJS, and I am trying to use ui-route.
I made a customer table that when you click on customer cart you can see the details of her/his shopping. CustomerId is supposed to pass as a parameter to the state.
<a ui-sref="order{{ cust.id }}" class="color-violet"><i class="fa fa-shopping-cart"></i></a>
but I receive an error of
Could not resolve 'order1' from state 'home'
Here is codes: customers.html
<!-- views/customers.html -->
<div class="container">
<div class="row" ng-cloack>
<h2>Customers</h2>
<br>
<form>
<div class="form-group">
<label>Filter</label>
<input type="text" class="form-control" data-ng-model="customerFilter.name">
</div>
</form>
<br>
<table class="table table-striped table-hover table-responsive">
<tr>
<th>#</th>
<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>
<th>View Order</th>
</tr>
<tr ng-repeat="cust in customers | filter:customerFilter | orderBy:sortBy:reverse">
<td>{{$index + 1 }}</td>
<td>{{cust.name | uppercase}}</td>
<td>{{cust.city}}</td>
<td>{{cust.orderTotal | currency}}</td>
<td>{{cust.joined | date}}</td>
<td><a ui-sref="order{{ cust.id }}" class="color-violet"><i class="fa fa-shopping-cart"></i></a></td>
</tr>
</table>
<span>Total customers: {{ customers.length}}</span>
</div>
orders.html
<!-- views/orders.html -->
<div class="container">
<div class="row" ng-cloack>
<h2>Orders</h2>
<br>
<table class="table table-striped table-hover table-responsive">
<tr>
<th>#</th>
<th>Product</th>
<th >Total</th>
</tr>
<tr ng-repeat="order in orders">
<td>{{$index + 1 }}</td>
<td>{{order.product}}</td>
<td>{{order.total | currency}}</td>
</tr>
</table>
</div>
app.js
(function() {
var app = angular.module('customersApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise("index.html")
$stateProvider
.state('home',
{
url:'/',
controller:'CustomersController',
templateUrl:'views/customers.html'
})
.state('order',{
url:'/order/:customerId',
controller: 'OrdersController',
templateUrl:'views/orders.html'
});
});
}());
and the controller of customer
(function() {
var CustomersController = function ($scope) {
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.customers = [
{id:1, joined: '2000-12-02', name:'Ali', city:'Montreal', orderTotal: 9.9956, orders: [ {id: 1, product:'Shoes', total: 9.9956}]},
{id:2, joined: '1965-01-25',name:'Zoe', city:'Montreal', orderTotal: 19.99, orders: [{id: 2, product:'Baseball', total: 9.995}, {id: 3, product:'Bat', total: 9.9956}]},
{id:3, joined: '1944-06-15',name:'Tina', city:'Toronto', orderTotal:44.99, orders: [{id: 4, product: 'Headphones', total: 44.99}]},
{id:4, joined: '1995-03-28',name:'Azad', city:'Vancouver', orderTotal:101.50, orders: [{id: 5, product: 'Kindle', total: 101.50}]}
];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
};
CustomersController.$inject = ['$scope'];
angular.module('customersApp')
.controller('CustomersController', CustomersController);
}());
and ordercontroller.js
(function() {
var OrdersController = function ($scope, $stateParams) {
// $routeParams.customerId comes from routing configuration customerId after PATH
var customerId = $stateParams.customerId;
$scope.orders = null;
function init() {
//Search the customers for the customerId
for (var i=0,len=$scope.customers.length;i<len;i++) {
if ($scope.customers[i].id === parseInt(customerId)) {
$scope.orders = $scope.customers[i].orders;
break;
}
}
}
$scope.customers = [
{id:1, joined: '2000-12-02', name:'Ali', city:'Montreal', orderTotal: 9.9956, orders: [ {id: 1, product:'Shoes', total: 9.9956}]},
{id:2, joined: '1965-01-25',name:'Zoe', city:'Montreal', orderTotal: 19.99, orders: [{id: 2, product:'Baseball', total: 9.995}, {id: 3, product:'Bat', total: 9.9956}]},
{id:3, joined: '1944-06-15',name:'Tina', city:'Toronto', orderTotal:44.99, orders: [{id: 4, product: 'Headphones', total: 44.99}]},
{id:4, joined: '1995-03-28',name:'Azad', city:'Vancouver', orderTotal:101.50, orders: [{id: 5, product: 'Kindle', total: 101.50}]}
];
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
};
init();
};
OrdersController.$inject = ['$scope', '$routeParams'];
angular.module('customersApp')
.controller('OrdersController', OrdersController);
}());
Everything looks fine, but I can realize where is this error coming from.
Thanks
You have to define which parameter you wish to use in the state (order). To do so treat the state like a function, and add all params as an object:
<a ui-sref="order({ customerId: cust.id })" class="color-violet"><i class="fa fa-shopping-cart"></i></a>
Here is a plunker I made. Whats the best approach to merge $scope.blacklistinto $scope.friends when ng-click="showColumn('Blacklist');" is fired, finally a new column called Coming need to be added to the table.
ng-app & ng-controller
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', MainCtrl]);
function MainCtrl($scope, $http) {
$scope.friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}];
$scope.coming = [{coming: 'x'},
{coming: 'x'},
{coming: 'x'},
{coming: 'x'},
{coming: 'x'}];
$scope.showColumn = function (type) {
if (type === 'coming') {
// INSERT Code here
console.log('Try add column coming');
}
}
$scope.getFilter = function () {
return $scope.filter;
};
$scope.setFilter = function (filter) {
$scope.filter = filter;
};
}
View
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<hr />
<a ng-click="showColumn('coming');">Show "coming"</a>
<hr />
<table class="table">
<tbody>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
<tr ng-repeat="friend in friends | filter:getFilter()">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</tbody>
</table>
</div>
</div>
Try
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope', MainCtrl]);
function MainCtrl($scope, $http) {
$scope.friends = [{
name: 'John',
phone: '555-1276'
}, {
name: 'Mary',
phone: '800-BIG-MARY'
}, {
name: 'Mike',
phone: '555-4321'
}, {
name: 'Adam',
phone: '555-5678'
}, {
name: 'Julie',
phone: '555-8765'
}];
$scope.coming = [{
coming: 'x'
}, {
coming: 'x'
}, {
coming: 'x'
}, {
coming: 'x'
}, {
coming: 'x'
}];
$scope.showColumn = function(type) {
if (type === 'coming') {
$scope.showComing = true;
angular.forEach($scope.friends, function(obj, i) {
obj.coming = ($scope.coming[i] || {}).coming;
})
}
}
$scope.getFilter = function() {
return $scope.filter;
};
$scope.setFilter = function(filter) {
$scope.filter = filter;
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<hr />
<a ng-click="showColumn('coming');">Show "coming"</a>
<hr />
<table class="table">
<tbody>
<tr>
<th>Name</th>
<th>Phone</th>
<th ng-show="showComing">Coming</th>
</tr>
<tr ng-repeat="friend in friends | filter:getFilter()">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td ng-show="showComing">{{friend.coming}}</td>
</tr>
</tbody>
</table>
</div>
</div>
I am trying to create a general table using element type custom directive that takes collection of data and generates the table header and create all the rows and columns of the table, then i tried to sort all the columns. The part of this code is working fine. But my next goal is to apply the filter on all the columns of the table, as the data is dynamic so we cannot decide about the field to filter at run time. The problem I diagnosed is that I am using ng-repeat="row in customers|filter:{$scope.searchkey:$scope.search}". Here seems to be the problem because in then expression the first thing should be object but $scope returns object.
Following is my code.
Index.html
<body>
<div>
<my-table input="Customers"></my-table>
<br />
<br />
<br />
<my-table input="Users"></my-table>
</div>
</body>
script.js
angular.module('DirectiveDemo', [])
.controller('Controller', ['$scope', function ($scope) {
$scope.Customers = [{ Name: "2Touqeer", Code: "2" },
{ Name: "3Nadeem", Code: "3" },
{ Name: "1Talha", Code: "1" },
{ Name: "4Muslim Khan", Code: "4" }
];
$scope.Users = [{ Name: "Touqeer", Code: "2", ID: "2Touqeer", CID: "CID1" },
{ Name: "Nadeem", Code: "3", ID: "3Muslim", CID: "CID3" },
{ Name: "Talha", Code: "1", ID: "1Nadeem", CID: "CID2" },
{ Name: "Muslim Khan", Code: "4", ID: "1Talha", CID: "CID5" },
{ Name: "Khan", Code: "4", ID: "1Khan", CID: "CID78" }
];
}])
.directive('myTable', function () {
return {
restrict: 'E',
transclude: true,
scope: {
customerInfo: '=input'
},
templateUrl: 'my-table-info.html',
controller: function ($scope) {
$scope.searchKey = 'CID';
alert($scope.searchKey)
$scope.reverseSort = false;
$scope.search = '';
$scope.List = [];
$scope.order = function (item) {
$scope.orderByField = item;
alert($scope.search)
}
$scope.filterValue = function (itemKey,valueKey) {
$scope.searchKey = itemKey;
if (valueKey != 'undefined') {
$scope.search = valueKey;
alert($scope.search)
}
}
}
};
})
my-table-info.html
<table ng-transclude>
<thead class="GridHeaderItem ControlBorder">
<tr>
<th ng-repeat="(key, value) in customerInfo[0]"> <a href="#" ng-click="order(key); reverseSort = !reverseSort">
{{key}}
<span ng-show="orderByField==key">
<span ng-show="!reverseSort">
<i class="glyphicon-circle-arrow-up glyphicon"></i>
</span>
<span ng-show="reverseSort">
<i class="glyphicon-circle-arrow-down glyphicon"></i>
</span></span>
</a></th>
</tr>
<tr class="ControlBorderRight ControlBorderTop ControlBorderBottom">
<td class=" ControlBorderLeft ControlBorderBottom" ng-repeat="(key, value) in customerInfo[0]" >
<input type="text" style="width:100%;" ng-model="searchfilter" ng-change="filterValue(key,searchfilter);" />
<!--ng-change="filter(key);"-->
</td>
</tr>
</thead>
<tr ng-repeat="row in customerInfo|filter:{co[row]:2}|orderBy:orderByField:reverseSort" class="ControlBorderRight ControlBorderTop ControlBorderBottom ">
<td ng-repeat="col in row" class=" ControlBorderBottom ControlBorderLeft Control LabelControl">{{col}}</td>
</tr>
</table>
You should build a custom filter function angular.module('myMod',[]).filter('myFilter',function(){ return function(input){...} }) then your repeat should look like this: ng-repeat="row in customers | myFilter" - the row object will be fed to the filter function as the input parameter.
Below is the code i am trying to execute but it is not routing to View1.
in View1 i am just looping through each element of Simplecontroller.
Please help.
<!DOCTYPE html>
<html data-ng-app="App">
<head>
<title>a</title>
</head>
<body>
<script src="Scripts/angular.min.js" type="text/javascript"></script>
<script src="Scripts/angular-route.min.js" type="text/javascript"></script>
<script type="text/javascript">
var App = angular.module('App', ['ngRoute']);
App.config(function ($routeProvider) {
$routeProvider
.when('/', { templateUrl: 'Partials/View1.htm', controller:'SimpleController' })
.when('/partial2', { templateUrl: 'Partials/View2.htm', controller: 'SimpleController' })
.otherwise({ redirectTo: '/AJTest' });
});
App.controller('SimpleController', function ($scope) {
$scope.customers =
[
{ name: 'a', city: 'a' },
{ name: 'b', city: 'b' },
{ name: 'c', city: 'c' },
{ name: 'd', city: 'd' }
];
$scope.addCustomer = function () {
$scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city });
}
});
</script>
<div data-ng-controller="SimpleController">
Name :<br />
<input type="text" data-ng-model="name" /> {{ name }}
<ul>
<li data-ng-repeat="cust in customers | filter:name | orderBy:city">{{ cust.name + ' ' + cust.city}} </li>
</ul>
</div>
</body>
</html>
thanks in advance.
All in all the "code" you posted doesn't make sense, first of all if you wish to use ngRoute and populate views with templates, you need a ng-view somewhere, secondly the code executes SimpleController which generates the expected output in the main application, not in a view... Anyways... Here is a Plunker that does what I think your trying to do:
http://plnkr.co/edit/oVSHzzjG3SrvpNsDkvDS?p=preview
Application:
var App = angular.module('App', ['ngRoute']);
App.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'view1.html',
controller: 'View1Controller'
})
.when('/partial2', {
templateUrl: 'view2.html',
controller: 'View2Controller'
})
.otherwise({
redirectTo: '/404'
});
});
App.controller('View1Controller', function($scope) {
$scope.customers = [{
name: 'a',
city: 'a'
}, {
name: 'b',
city: 'b'
}, {
name: 'c',
city: 'c'
}, {
name: 'd',
city: 'd'
}];
$scope.addCustomer = function() {
$scope.customers.push({
name: $scope.newCustomer.name,
city: $scope.newCustomer.city
});
}
});
App.controller('View2Controller', function($scope) {
$scope.hello = "BOOOO!";
});
Main Page:
<!DOCTYPE html>
<html ng-app="App">
<body>
VIEW 1 - VIEW 2
<div ng-view></div>
<script src="https://code.angularjs.org/1.2.16/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.16/angular-route.min.js"></script>
<script src="script.js" ></script>
</body>
</html>
View1:
HELLO FROM VIEW 1:
<br />
<br />Running through items in the view::
<br />Name :
<br />
<input type="text" data-ng-model="name" />{{ name }}
<ul>
<li data-ng-repeat="cust in customers | filter:name | orderBy:city">{{ cust.name + ' ' + cust.city}}</li>
</ul>