Injected service undefined - javascript

I have 2 javascript files, one used as a controller and second as service. When I am injecting service into controller and access it's function, it says
var app = angular.module('currencyConverterModule', []);
app.factory('currencyConverter', function() {
var localToINR = [
{USD: 0.015},
{GBP: 0.011}
];
var convertToLocalCurrency = function (amount, localCurrency) {
return amount * localToINR[localCurrency];
}
return { convertToLocalCurrency };
});
var app = angular.module('cartModule', ['currencyConverterModule']);
app.controller('cartController', ['$scope', 'currencyConverter', function ($scope, currencyConverter){
$scope.SelectedCountry = '0';
$scope.localCurrency = function(amount, currencyConverter) {
currencyConverter.convertToLocalCurrency(amount, $scope.SelectedCountry);
}
$scope.Products = [
{name: 'TV', price: $scope.localCurrency(30000), quantity: 1},
{name: 'Fridge', price: $scope.localCurrency(35000), quantity: 1},
{name: 'AC', price: $scope.localCurrency(40000), quantity: 1}
];
$scope.Countries = [
{name: 'India', currency: 'INR', currencySymbol: '&#8377'},
{name: 'United States', currency: 'USD', currencySymbol: '$'},
{name: 'England', currency: 'GBP', currencySymbol: '£'}
];
$scope.getCartValue = function () {
var total = 0;
for (var i = 0; i < $scope.Products.length; i++) {
total = $scope.Products[i].price * $scope.Products[i].quantity;
}
return total;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="cartModule" ng-controller="cartController">
<table ng-hide="SelectedCountry == '0'">
<tr>
<th>Product</th>
<th>Price Per Unit</th>
<th> Quantity</th>
<th>Total Price</th>
</tr>
<tr ng-repeat="product in Products">
<td ng-bind="product.name">
</td>
<td ng-bind="product.price | currency : '&#8377'"></td>
<td>
<input type="number" ng-model="product.quantity" min="0" max="100">
</td>
<td ng-bind="product.price * product.quantity | currency : '&#8377'"></td>
</tr>
<tr>
<th colspan="3">Total</th>
<th ng-bind="getCartValue() | currency : '&#8377'"></th>
</tr>
</table>
<select ng-model="SelectedCountry">
<option value="0">Select your country</option>
<option ng-repeat="country in Countries" ng-value="country.name" ng-bind="country.name"></option>
</select>
</div>
</body>
TypeError: Cannot read property 'methodName' of undefined
Service
var app = angular.module('currencyConverterModule', []);
app.factory('currencyConverter', function() {
var localToINR = [
{USD: 0.015},
{GBP: 0.011}
];
var convertToLocalCurrency = function (amount, localCurrency) {
return amount * localToINR[localCurrency];
}
return { convertToLocalCurrency };
});
and Controller
var app = angular.module('cartModule', ['currencyConverterModule']);
app.controller('cartController', ['currencyConverter', function ($scope, currencyConverter){
$scope.SelectedCountry = '0';
$scope.localCurrency = function(amount, currencyConverter) {
currencyConverter.convert(amount, $scope.SelectedCountry); //Error here
}
$scope.Products = [
{name: 'TV', price: $scope.localCurrency(30000), quantity: 1},
{name: 'Fridge', price: $scope.localCurrency(35000), quantity: 1},
{name: 'AC', price: $scope.localCurrency(40000), quantity: 1}
];
$scope.Countries = [
{name: 'India', currency: 'INR', currencySymbol: '&#8377'},
{name: 'United States', currency: 'USD', currencySymbol: '$'},
{name: 'England', currency: 'GBP', currencySymbol: '£'}
];
$scope.getCartValue = function () {
var total = 0;
for (var i = 0; i < $scope.Products.length; i++) {
total = $scope.Products[i].price * $scope.Products[i].quantity;
}
return total;
}
}]);
I have tried adding both files in different order in view but that couldn't solve the problem. What I am doing wrong here?
I am referencing 3 js files in HTML as below
<script src="../Script/angular.js"></script>
<script src="../Services/currencyConverter.js"></script>
<script src="../Script/cartController.js"></script>

You have missed to inject $scope,
app.controller('cartController', ['$scope','currencyConverter', function ($scope, currencyConverter)
and the method name is convertToLocalCurrency not just convert
currencyConverter.convertToLocalCurrency(amount, $scope.SelectedCountry);
EDIT
You're getting undefined because your function parameter name is also currencyConverter , you need to change it to something else or remove it completely since you are not using,
$scope.localCurrency = function(amount, currency) {
currencyConverter.convertToLocalCurrency(amount, $scope.SelectedCountry);
}
WORKING DEMO
Also i modified your service a bit to return the factory with the methods as
var app = angular.module('currencyConverterModule', []);
app.factory('currencyConverter', function() {
var dataFactory={};
var localToINR = [
{USD: 0.015},
{GBP: 0.011}
];
dataFactory.convertToLocalCurrency = function (amount, localCurrency) {
return amount * localToINR[localCurrency];
}
return dataFactory ;
});

The $scope.localCurrency function erroneously has two parameters:
app.controller('cartController', ['$scope', 'currencyConverter',
function ($scope, currencyConverter){
$scope.SelectedCountry = '0';
$̶s̶c̶o̶p̶e̶.̶l̶o̶c̶a̶l̶C̶u̶r̶r̶e̶n̶c̶y̶ ̶=̶ ̶f̶u̶n̶c̶t̶i̶o̶n̶(̶a̶m̶o̶u̶n̶t̶,̶ ̶c̶u̶r̶r̶e̶n̶c̶y̶C̶o̶n̶v̶e̶r̶t̶e̶r̶)̶ ̶{
$scope.localCurrency = function(amount) {
currencyConverter.convertToLocalCurrency(amount, $scope.SelectedCountry);
}
The currencyConverter factory is injected in controller construction function, not in the local scope function.
The DEMO
var app = angular.module('currencyConverterModule', []);
app.factory('currencyConverter', function() {
var localToINR = [
{USD: 0.015},
{GBP: 0.011}
];
var convertToLocalCurrency = function (amount, localCurrency) {
return amount * localToINR[localCurrency];
}
return { convertToLocalCurrency };
});
var app = angular.module('cartModule', ['currencyConverterModule']);
app.controller('cartController', ['$scope', 'currencyConverter', function ($scope, currencyConverter){
$scope.SelectedCountry = '0';
$scope.localCurrency = function(amount) {
currencyConverter.convertToLocalCurrency(amount, $scope.SelectedCountry);
}
$scope.Products = [
{name: 'TV', price: $scope.localCurrency(30000), quantity: 1},
{name: 'Fridge', price: $scope.localCurrency(35000), quantity: 1},
{name: 'AC', price: $scope.localCurrency(40000), quantity: 1}
];
$scope.Countries = [
{name: 'India', currency: 'INR', currencySymbol: '&#8377'},
{name: 'United States', currency: 'USD', currencySymbol: '$'},
{name: 'England', currency: 'GBP', currencySymbol: '£'}
];
$scope.getCartValue = function () {
var total = 0;
for (var i = 0; i < $scope.Products.length; i++) {
total = $scope.Products[i].price * $scope.Products[i].quantity;
}
return total;
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="cartModule" ng-controller="cartController">
<table ng-hide="SelectedCountry == '0'">
<tr>
<th>Product</th>
<th>Price Per Unit</th>
<th> Quantity</th>
<th>Total Price</th>
</tr>
<tr ng-repeat="product in Products">
<td ng-bind="product.name">
</td>
<td ng-bind="product.price | currency : '&#8377'"></td>
<td>
<input type="number" ng-model="product.quantity" min="0" max="100">
</td>
<td ng-bind="product.price * product.quantity | currency : '&#8377'"></td>
</tr>
<tr>
<th colspan="3">Total</th>
<th ng-bind="getCartValue() | currency : '&#8377'"></th>
</tr>
</table>
<select ng-model="SelectedCountry">
<option value="0">Select your country</option>
<option ng-repeat="country in Countries" ng-value="country.name" ng-bind="country.name"></option>
</select>
</div>
</body>

Related

Angularjs: How do I ng-repeat through an array of objects with a field that is also an array?

I have an array that looks like this:
0: {ID: null,
name: "test",
city: "Austin",
UserColors: [{color: "blue"},{hobby:"beach"} ... ]}
}...
I am trying to ng-repeat through the initial array but once I try to loop through the list, i see nothing, heres the html/angular
<tr ng-repeat="c in vm.people">
<td>{{c.name}}</td>
<td>{{c.city}}</td>
<td ng-repeat="uc in c.UserColors">
<td>{{uc.color}}</td>
</td>
</tr>
I am not sure what is wrong, and I would appreciate your help, I thank you in advance.
I would process the field with a custom filter:
<td ng-repeat-start="(key, value) in c.UserColors | reduce">
<b>{{key}}</b>
</td>
<td ng-repeat-end>
{{value}}
</td>
The filter:
app.filter("reduce",function() {
return function(items) {
var x = items.map(o => Object.entries(o));
var x2 = x.reduce(((a,x) => (a.concat(x))), []);
var x3 = x2.reduce(((o,x) => (o[x[0]]=x[1],o)), {});
return x3;
}
})
The DEMO
angular.module("app",[])
.controller("ctrl",function(){
var vm = this;
vm.people = {
0: {ID: null,
name: "test",
city: "Austin",
UserColors: [{color: "blue"},{hobby:"beach"}]
},
1: {ID: null,
name: "best",
city: "Boston",
UserColors: [{colorx: "red"},{shirt:"black"}]
},
2: {ID: null,
name: "rest",
city: "Paris",
UserColors: [{colory: "yel"},{fruit:"peach"}]
},
}
})
.filter("reduce",function() {
return function(items) {
var x = items.map(o => Object.entries(o));
var x2 = x.reduce(((a,x) => (a.concat(x))), []);
var x3 = x2.reduce(((o,x) => (o[x[0]]=x[1],o)), {});
return x3;//items;
}
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl as vm">
<h3>Table</h3>
<table>
<tr ng-repeat="c in vm.people">
<td>{{c.name}}</td>
<td>{{c.city}}</td>
<td ng-repeat-start="(key, value) in c.UserColors | reduce">
<b>{{key}}</b>
</td>
<td ng-repeat-end>
{{value}}
</td>
</tr>
</table>
</body>

How to count the number of rows containing a certain value?

I'm using AngularJS and I have a table that I populate using ng-repeat. Check this short example:
http://jsfiddle.net/sso3ktz4/
How do I check how many rows I have with a certain value? For example, in the fiddle above, how do I check how many rows I have with the word "second"? It should return "3".
AngularJS answers are preferred, although I also have JQuery available.
Thanks!
updated controller code is below, where $scope.findRowCount is required function
var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.items = [{
name: 'first',
examples: [{
name: 'first 1'
}, {
name: 'first 2'
}]
}, {
name: 'second',
examples: [{
name: 'second'
}, {
name: 'second'
}]
}];
$scope.findRowCount=function(value){
var count=0;
angular.forEach($scope.items, function(item, i){
if(item.name==value){
count=count+1;
}
angular.forEach(item.examples, function(exp, j){
if(exp.name==value){
count=count+1;
}
})
});
console.log("count"+count);
return count;
}
var result=$scope.findRowCount("second");
console.log(result);
}
http://jsfiddle.net/p3g9vyud/
Try this way
var myApp = angular.module('myApp', []).controller('MyCtrl', MyCtrl);
function MyCtrl($scope) {
$scope.items = [{
name: 'first',
examples: [{
name: 'first 1'
}, {
name: 'first 2'
}]
}, {
name: 'second',
examples: [{
name: 'second'
}, {
name: 'second'
}]
}];
//Get sum based on the label
$scope.getTotalByLabel = function(keyword)
{
$scope.totalSecond = 0;
angular.forEach($scope.items, function(value, key) {
if(value.name == keyword)
{
$scope.totalSecond += 1;
}
angular.forEach(value.examples, function(val, k) {
if(val.name == keyword)
{
$scope.totalSecond += 1;
}
});
});
return $scope.totalSecond;
}
}
th,
td {
padding: 7px;
text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<table border="1">
<tbody ng:repeat="i in items">
<tr>
<td>{{i.name}}</td>
<td>{{$index}}</td>
</tr>
<tr ng:repeat="e in i.examples">
<td>{{e.name}}</td>
<td>{{$index}}</td>
</tr>
</tbody>
</table>
<b>Total of second</b>: {{getTotalByLabel('second')}}
</div>
</div>

Pagination with filters using ng-repeat in angular

I am trying to do a pagination using filters.
There is a list with names and countries.
I am trying to filter them by country and also alphabetical range, and then generate the pagination by numbers. I am really stuck with it. any help will be really appreciate it
The alphabetical filter will retrieve the names that start with the the range of letters. For example if you select the first option [A - M] will return the person that their name start within that range of letters
Here is my code. The html is over there. Thanks
http://jsbin.com/cifowatuzu/edit?html,js,output
angular.module('app',['angular.filter'])
.controller('MainController', function($scope) {
$scope.selectedCountry = '';
$scope.currentPage = 1;
$scope.pageSize = 3;
$scope.pages = [];
//This should store {StartFrom and To from selected Range}
$scope.selectedRange = '';
$scope.AlphabethicalRange = [
{StartFrom: 'A', To: 'M'},
{StartFrom: 'N', To: 'Z'}
];
$scope.Countries = [
{ Name : 'USA'},
{ Name : 'Japan'},
{ Name : 'France'},
{ Name : 'Canada'},
{ Name : 'China'},
];
$scope.People = [
{ Id: 1, Name: 'Will', Country: 'USA'},
{ Id: 2, Name: 'Ed', Country: 'USA' },
{ Id: 3, Name: 'Peter', Country: 'China'},
{ Id: 4, Name: 'John', Country: 'Japan'},
{ Id: 5, Name: 'Alex', Country: 'France'},
{ Id: 6, Name: 'Jim', Country: 'France'},
{ Id: 7, Name: 'Austin', Country: 'Italy'},
{ Id: 8, Name: 'Men', Country: 'France'},
{ Id: 9, Name: 'Zike', Country: 'Canada'},
];
$scope.numberPages = Math.ceil($scope.People.length / $scope.pageSize);
$scope.init = function () {
for (i = 1; i < $scope.numberPages; i++) {
$scope.pages.push(i);
}
};
$scope.init();
});
I create a custom filter to filter the range that you want.
Here's a snippet working:
var app = angular.module('app', ['angular.filter']);
app.controller('mainCtrl', function ($scope) {
$scope.currentPage = 1;
$scope.pageSize = 3;
$scope.pages = [];
$scope.AlphabethicalRange = [
{
"StartFrom":"A",
"To":"M"
},
{
"StartFrom":"N",
"To":"Z"
}
];
$scope.Countries = [
{
"Name":"USA"
},
{
"Name":"Japan"
},
{
"Name":"France"
},
{
"Name":"Canada"
},
{
"Name":"China"
}
];
$scope.People = [
{
"Id":1,
"Name":"Will",
"Country":"USA"
},
{
"Id":2,
"Name":"Ed",
"Country":"USA"
},
{
"Id":3,
"Name":"Peter",
"Country":"China"
},
{
"Id":4,
"Name":"John",
"Country":"Japan"
},
{
"Id":5,
"Name":"Alex",
"Country":"France"
},
{
"Id":6,
"Name":"Jim",
"Country":"France"
},
{
"Id":7,
"Name":"Austin",
"Country":"Italy"
},
{
"Id":8,
"Name":"Men",
"Country":"France"
},
{
"Id":9,
"Name":"Zike",
"Country":"Canada"
}
];
$scope.numberPages = Math.ceil($scope.People.length / $scope.pageSize);
$scope.init = function() {
for (i = 1; i < $scope.numberPages; i++) {
$scope.pages.push(i);
}
};
$scope.init();
});
app.filter('rangeAlphaFilter', function() {
return function(items, search) {
if (!search || search == ' - ') {
return items;
}
return items.filter(function(element) {
return new RegExp('[' + search.replace(/ /g, '') + ']', 'i').test(element.Name[0]);
});
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div>
<span>Country Filter</span>
<select name="countriesSelect" ng-options="c as c.Name for c in Countries" ng-model="selectedCountry">
<option value="">-- Select a country --</option>
</select>
<br>
<span>Alphabetical Filter</span>
<select name="AlphabeticalSelect" ng-options="a as a.StartFrom +' - '+ a.To for a in AlphabethicalRange" ng-model="selectedRange">
<option value="">-- Select a range --</option>
</select>
<ul>
<li ng-repeat="person in People | filter: { Country: selectedCountry.Name } | rangeAlphaFilter: selectedRange.StartFrom +' - '+ selectedRange.To" ng-bind="person.Name"></li>
</ul>
<span>Pagination Numbers</span>
{{page}}
</div>
</body>
</html>
PS: To control the pagination, I extremely don't recommend you to do it manually, it gives a lot of work. I recommend you to see my answer in this another question, it's like a "mini" tutorial of how to use the angularUtils-pagination. Check it.
I hope it helps.

Could not resolve 'state1' from state 'state' while having parameters in the url link

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>

Add column in table by merging object attributes

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>

Categories