I am trying to show a list of payments made for a particular product. So, if i purchased a product for $2000, i would could set up a monthly payment of $100 and i want to try and track if that payment is made or not.
I have a nested ng-repeat. The first repeat displays a list of products as well as an associated id. For example:
Bed frame | ID: po8j3mau72
Television | ID: hyf53ygt65
Fridge | ID: gytf87hg5d
The second repeat displays the monthly payment made.
What i want to try and show is something like this:
Bedframe:
Jan Feb Mar Apr May Jun.....
2016 Y Y Y N Y N
2015 Y N
...
...
Television:
Jan Feb Mar Apr May Jun.....
2016 Y N Y N Y N
2015 Y Y Y Y Y Y
...
...
Where Y = contentHistory.paid = true
Where N = contentHistory.paid = false
Dates should be sorted from Jan - Dec for each year and format recieved in .JSON is paymentDate":"2016-03-28T00:00:00.000Z",
HTML:
<ul>
<li ng-repeat-start="item in myItem.items">
{{item.addressLine1}} | ID: {{item._id}}
</li>
<li ng-repeat-end>
<div ng-repeat="info in contents[item._id].contentHistory">
{{info.amount}}
</div>
</li>
</ul>
Controller:
app.controller('MainCtrl', function($scope, myService) {
$scope.test = 'hello';
myService.getItemModel(function(itemModel) {
$scope.myItem = itemModel;
$scope.contents = {};
var itemList = itemModel.items;
itemList.forEach(function(item) {
var addressId = item._id;
myService.getContentModel(addressId)
.success(function (data, status, headers, config) {
$scope.contents[addressId] = data;
console.log(arguments);
console.log($scope.contents);
})
.error(function (data, status, headers, config) {
});
});
});
});
Service:
app.factory('myService', function($http, $q) {
return {
getItemModel: function(itemModel) {
$http.get('itemID.json')
.success(function(data) {
itemModel(data);
})
.error(function(error) {
alert('An error occured whilst trying to retrieve your item data');
});
},
getContentModel: function(addressId) {
return $http({
method: 'GET',
url: addressId + '.json',
headers: {'Content-Type': 'application/json'}
});
}
}
});
Plunker: https://plnkr.co/edit/KIMScMfUdgCdOKksVyAs
just implemented this.modified your markup a little.and added new properties Year and Month to content history item.check this plunker
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, myService) {
$scope.test = 'hello';
myService.getItemModel(function(itemModel) {
$scope.myItem = itemModel;
$scope.contents = {};
var itemList = itemModel.items;
itemList.forEach(function(item) {
var addressId = item._id;
myService.getContentModel(addressId)
.success(function(data, status, headers, config) {
angular.forEach(data.contentHistory, function(v) {
v.paymentDate = new Date(v.paymentDate);
v.Year = v.paymentDate.getFullYear();
v.Month = v.paymentDate.getMonth();
});
$scope.contents[addressId] = data;
})
.error(function(data, status, headers, config) {
});
});
});
$scope.months = [{
n: 0,
name: 'Jan'
}, {
n: 1,
name: 'Feb'
}, {
n: 2,
name: 'Mar'
}, {
n: 3,
name: 'Apr'
}, {
n: 4,
name: 'May'
}, {
n: 5,
name: 'Jun'
}, {
n: 6,
name: 'Jul'
}, {
n: 7,
name: 'Aug'
}, {
n: 8,
name: 'Sep'
}, {
n: 9,
name: 'Oct'
}, {
n: 10,
name: 'Nov'
}, {
n: 11,
name: 'Dec'
}];
$scope.getData = function(data, year, month) {
var rd = data.filter(function(d) {
return d.Year == year && d.Month == month
});
if (rd.length > 0)
return rd[0].amount;
return 'x';
};
$scope.getUniqueYears = function(data) {
var years = [];
angular.forEach(data, function(v) {
if (years.indexOf(v.Year) == -1) {
years.push(v.Year);
}
});
return years;
};
});
app.factory('myService', function($http, $q) {
return {
getItemModel: function(itemModel) {
$http.get('itemID.json')
.success(function(data) {
itemModel(data);
})
.error(function(error) {
alert('An error occured whilst trying to retrieve your item data');
});
},
getContentModel: function(addressId) {
return $http({
method: 'GET',
url: addressId + '.json',
headers: {
'Content-Type': 'application/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 href="style.css" rel="stylesheet" />
<script data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js" data-require="angular.js#1.4.x"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>{{test}}!</p>
<div>
<h4 ng-repeat-start="item in myItem.items">
{{item.addressLine1}} | ID: {{item._id}}
</h4>
<div ng-repeat-end>
<table>
<tr>
<td>Year</td>
<td ng-repeat="month in months">
{{month.name}}
</td>
</tr>
<tr ng-repeat="year in getUniqueYears(contents[item._id].contentHistory)">
<td>{{year}}</td>
<td ng-repeat="month in months">
{{getData(contents[item._id].contentHistory,year,month.n)}}
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
Related
I'm trying to find a better way for rendering a large table in Angular than using ngRepeat.
I tried using one-time {{::binding}}s, but found the initial render time remained unchanged, which wasn't satisfactory.
Back to the drawing board, I'm trying to find a much more performant method for assembling data into a HTML table in the DOM. I've been trying to use angular.element() to assemble all the parts into a whole, but with no luck. Any insights?
var app = angular.module('app', []);
app.directive('myTable', function() {
return {
restrict: 'E',
scope: {
ngModel: "=",
},
require: 'ngModel',
link: function(scope, element, attrs) {
scope.$watch('ngModel', function() {
if (typeof scope.ngModel == 'undefined') {
console.log("ngModel not defined yet");
return;
}
element.html('');
var table = angular.element('<table/>');
var tbody = angular.element('<tbody/>');
scope.ngModel.forEach(function(m) {
var tr = angular.element('<tr/>');
m.fields.forEach(function(f) {
var td = angular.element('<td/>')
td.text(f.value);
td.append(tr);
});
tr.append(tbody);
})
tbody.append(table);
table.append(element);
})
}
}
});
app.controller('AppController', function($scope) {
$scope.data = [{
fields: [{
value: 1,
metadata: ""
}, {
value: 2,
metadata: ""
}, {
value: 3,
metadata: ""
}, {
value: 4,
metadata: ""
}, {
value: 5,
metadata: ""
}, ]
},
{
fields: [{
value: 6,
metadata: ""
}, {
value: 7,
metadata: ""
}, {
value: 8,
metadata: ""
}, {
value: 9,
metadata: ""
}, {
value: 10,
metadata: ""
}, ]
}
]
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="app" ng-controller="AppController">
<my-table ng-model="data"></my-table>
</div>
</body>
It is inappropriate to involve the ngModel controller in a directive that has no user input elements. Also isolate scope is unnecessary. Evaluate the table-data attribute in the watch expression.
Also of course, fix the backwards append statements:
app.directive('myTable', function() {
return {
restrict: 'E',
̶s̶c̶o̶p̶e̶:̶ ̶{̶
̶n̶g̶M̶o̶d̶e̶l̶:̶ ̶"̶=̶"̶,̶
̶}̶,̶
̶r̶e̶q̶u̶i̶r̶e̶:̶ ̶'̶n̶g̶M̶o̶d̶e̶l̶'̶,̶
link: function(scope, element, attrs) {
scope.$watch(attrs.tableData ̶'̶n̶g̶M̶o̶d̶e̶l̶'̶, function(data) {
if (data) {
console.log("table-data not defined yet");
return;
}
element.html('');
var table = angular.element('<table/>');
var tbody = angular.element('<tbody/>');
data.forEach(function(m) {
var tr = angular.element('<tr/>');
m.fields.forEach(function(f) {
var td = angular.element('<td/>')
td.text(f.value);
̶t̶d̶.̶a̶p̶p̶e̶n̶d̶(̶t̶r̶)̶;̶ tr.append(td);
});
̶t̶r̶.̶a̶p̶p̶e̶n̶d̶(̶t̶b̶o̶d̶y̶)̶;̶ tbody.append(tr);
})
̶t̶b̶o̶d̶y̶.̶a̶p̶p̶e̶n̶d̶(̶t̶a̶b̶l̶e̶)̶;̶ table.append(tbody);
̶t̶a̶b̶l̶e̶.̶a̶p̶p̶e̶n̶d̶(̶e̶l̶e̶m̶e̶n̶t̶)̶;̶ element.append(table);
})
}
}
});
Usage:
<my-table table-data="data"></my-table>
THE DEMO
var app = angular.module('app', []);
app.directive('myTable', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.$watch(attrs.tableData, function(data) {
console.log(data);
if (!data) {
console.log("tableData not defined yet");
return;
}
element.html('');
var table = angular.element('<table/>');
var tbody = angular.element('<tbody/>');
data.forEach(function(m) {
var tr = angular.element('<tr/>');
m.fields.forEach(function(f) {
var td = angular.element('<td/>')
td.text(f.value);
tr.append(td);
});
tbody.append(tr);
})
table.append(tbody);
element.append(table);
})
}
}
});
app.controller('ctrl', function($scope) {
$scope.data = [{
fields: [{
value: 1,
metadata: ""
}, {
value: 2,
metadata: ""
}, {
value: 3,
metadata: ""
}, {
value: 4,
metadata: ""
}, {
value: 5,
metadata: ""
}, ]
},
{
fields: [{
value: 6,
metadata: ""
}, {
value: 7,
metadata: ""
}, {
value: 8,
metadata: ""
}, {
value: 9,
metadata: ""
}, {
value: 10,
metadata: ""
}, ]
}
]
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="ctrl">
<my-table table-data="data"></my-table>
</body>
I have an issue as i am trying to retrieve data from jsp in angularjs. Is it feasible? If not.. what are other ways to get retrieve data in angular js controller. Can anyone else help me out to get solution. My Code is given below....
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-sanitize.min.js"></script>
<script>
angular.module("myApp", []).controller('testController',['$scope', '$http', '$log', function($scope, $http, $log)
{
var stateNameHindi = "";
var stateLandingPageUrl = "";
$scope.ScopeObject = {
states : [
{ name: "राज्य चुनें", Ename: "select", district: [{Hnname: 'जिला चुनें', DEname: "Select" }] },
{ name: "राजस्थान ", Ename: "Rajasthan", district: [{ Hnname: 'जयपुर' , DEname: "jaipur"}] },
{ name: "छत्तीस गढ़ ", Ename: "Chattisgarh", district: [{ Hnname: 'बिलास पुर', DEname: "Bilaspur"}, { Hnname: 'रायपुर', DEname: "raipur"}] },
{ name: "गुजरात ", Ename: "Gujrat", district: [ { Hnname: 'अहमदाबाद', DEname: "Ahmdabad"}, { Hnname: 'सूरत', DEname: "surat"}, { Hnname: 'वड़ोदरा', DEname: "vadodra"} ] }
],
} ;
$scope.selectAction = function(EngStateName, EngCityName ) {
var state = EngStateName.Ename;
var city = EngCityName.DEname;
$scope.CityData = $http.get('/xyz/CityNews.jsp',
{
params:{state: state, city: city}})
.then(function(response)
{
if (response.status == 200){
alert("mayank");
$scope.CityData = JSON.parse(response);
alert("sing" + $scope.CityData);
$log.info(response);}
}, function myError(response) {
$scope.CityData = response.statusText;
});
};
$scope.StateSelect = function(EngStateName) {
var state = EngStateName.Ename;
$scope.StateData = $http.get('/xyz/CityNews.jsp',
{
params:{state: state}})
.then(function(response)
{
if (response.status == 200){
alert("mayank");
$scope.StateData = JSON.stringify(response);
var data = JSON.parse($scope.CityData)
alert("sing" + data);
$log.info(response);}
}, function myError(response) {
$scope.CityData = response.statusText;
});
};
}]);
</script>
<div ng-app="myApp">
<div ng-controller="testController">
<select name="state" ng-options="c.name for c in ScopeObject.states track by c.Ename" ng-model="ScopeObject.SelectedData" ng-change="StateSelect(ScopeObject.SelectedData)">
<option value=''>राज्य चुनें</option>
</select>
<select district="cityname" ng-options="d.Hnname for d in ScopeObject.SelectedData.district track by d.DEname" ng-model="ScopeObject.cityname" ng-change="selectAction(ScopeObject.SelectedData, ScopeObject.cityname )">
<option value=''>जिला चुनें</option>
</select>
<p> {{CityData}} </p>
<p> {{StateData}} </p>
</div>
</div>
I am trying to open a modal popup with table. How can I do this? In my app.js, on the click event of row open a modal, I also want to update some field with the selected item value. But i can't update with selected value.
my app.js
var tableApp = angular.module('tableApp', ['ui.bootstrap']);
tableApp.controller('tableController', function ($scope,$rootScope, $filter, $modal) {
$scope.filteredPeople = [];
$scope.currentPage = 1;
$scope.pageSize = 10;
$scope.people = [{ id: "1", name: "joe",disable:true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe", disable: true },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true },
{ id: "1", name: "joe" },
{ id: "2", name: "bill", disable: true },
{ id: "3", name: "john", disable: true }];
$scope.getPage = function () {
var begin = (($scope.currentPage - 1) * $scope.pageSize);
var end = begin + $scope.pageSize;
$scope.filteredPeople = $filter('filter')($scope.people, {
id: $scope.idFilter,
name: $scope.nameFilter
});
$scope.totalItems = $scope.filteredPeople.length;
$scope.filteredPeople = $scope.filteredPeople.slice(begin, end);
};
$scope.getPage();
$scope.pageChanged = function () {
$scope.getPage();
};
$scope.open = function () {
$scope.id = generateUUID();
};
$scope.dblclick = function (index) {
for (var i = 0; i < $scope.filteredPeople.length; i++) {
$scope.filteredPeople[i].disable = true;
}
return index.disable = false;
}
$scope.rowSelect = function (rowdata) {
alert(rowdata.name);
}
});
tableApp.controller('DetailModalController', [
'$scope', '$modalInstance', 'item',
function ($scope, $modalInstance, item) {
$scope.item = item;
$scope.dismiss = function () {
$modalInstance.dismiss();
};
$scope.close = function () {
$modalInstance.close($scope.item);
};
}]);
tableApp.directive('myModal', function ($log, $compile) {
var parm = [];
return {
restrict: 'E',
templateUrl: 'modalBase.html',
scope: {
modal: '=',
idF:'='
},
link: function (scope, element, attrs) {
debugger;
parm.name = attrs.idf;
}
//controller: function ($scope) {
// debugger;
// console.log($scope);
// $scope.selected = {
// item: $scope.modal.items[0]
// };
// $scope.ok = function () {
// debugger;
// alert(parm.name);
// $scope.modal.instance.close($scope.selected);
// };
// $scope.cancel = function () {
// $scope.modal.instance.dismiss('cancel');
// };
// $scope.modal.instance.result.then(function (selectedItem) {
// $scope.selected = selectedItem;
// }, function () {
// $log.info('Modal dismissed at: ' + new Date());
// });
//}
};
});
As I understand, you use angular.ui. I would suggesst you to use $modal service instead of $modalInstance. Using that you can call your modal instance with $modal.open(). And also you don't need to close it in your controller - place appropriate methods on your modal template and it will work by its services
Template:
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
{{ item }}
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="$close()">OK</button>
<button class="btn btn-warning" type="button" ng-click="$dismiss('cancel')">Cancel</button>
</div>
</script>
Controlelr
var modalInstance = $uibModal.open({
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
You can find more info about it in angular.ui documentation for modals
I am building a tag-manager in an angular form that uses two dropdown menus (in this demo a food category and a specific item). When the user selects a food category the item dropdown should appear, and when that dropdown has a value selected the I want a string added to my tag list in the format of ': '. Below is the code:
app.js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope){
$scope.tags = [];
$scope.userCategory;
$scope.userFood;
$scope.primaryFoods = [
{
'id': 1,
'parent_id': null,
'name': 'Pizza'
},
{
'id': 4,
'parent_id': null,
'name': 'Burgers'
},
{
'id': 7,
'parent_id': null,
'name': 'Pasta'
},
];
$scope.secondaryFoods = [
{
'id': 2,
'parent_id': 1,
'name': 'Cheese Pizza'
},
{
'id': 3,
'parent_id': 1,
'name': 'Combo Pizza'
},
{
'id': 5,
'parent_id': 4,
'name': 'Cheese Burgers'
},
{
'id': 6,
'parent_id': 4,
'name': 'Hamburgers'
},
];
});
app.directive('doubleTagManager', function() {
return {
restrict: 'E',
scope: {tags: '=', primary: '=', secondary: '=', userPrimary: '=', userSecondary: '='},
templateUrl: 'double-tag-manager.html',
link: function ($scope, $element) {
var input = angular.element($element.find('select')[1]);
// This adds the new tag to the tags array in '<Primary>: <Secondary>' format
$scope.add = function() {
var new_value = input[0].value;
if ($scope.tags.indexOf(new_value) < 0) {
$scope.tags.push($scope.userPrimary.name + ': ' + $scope.userSecondary.name);
}
};
// This is the ng-click handler to remove an item
$scope.remove = function (idx) {
$scope.tags.splice(idx, 1);
};
input.bind( 'change', function (event) {
$scope.$apply($scope.add);
});
}
};
});
double-tag-manager.html
<div class="row">
<div class="col-md-6">
<select name="uFoodsPrimary" id="foodPrimary" class="form-control"
ng-model="userPrimary"
ng-options="item.name for item in primary track by item.name" required>
<option value="">Select a Food category!</option>
</select>
</div>
<div class="col-md-6" ng-show="userPrimary">
<select name="uFoodsSecondary" id="foodSecondary" class="form-control"
ng-model="userSecondary"
ng-options="item.name for item in (secondary | filter: {parent_id: userPrimary.id})
track by item.name"
required>
<option value="">Select a Food sub-category!</option>
</select>
</div>
</div>
<div class="tags">
<a ng-repeat="(idx, tag) in tags" class="tag" ng-click="remove(idx)">{{tag}}</a>
</div>
What I would like to add is the ability to select 'All foods' so users don't need to select all the items individually but I cannot seem to figure out how to add an additional field using ng-options.
Fiddle
BONUS: If a category is selected that has no children I would like it added to the tags list by default.
Erik,
Here is the modified code to achieve your all select feature. Further you can enhance it more to achieve your BONUS use case.
Rather than putting too much effort to achieve tagging in this way, I would suggest to use existing angularui-select2 component. It has lot of other options also. It will make your life more easy.
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.tags = [];
$scope.sub_cat_show = false;
$scope.all_sub_cat_show = false;
$scope.userCategory;
$scope.userFood;
$scope.primaryFoods = [{
'id': 0,
'parent_id': null,
'name': 'All Foods'
}, {
'id': 1,
'parent_id': null,
'name': 'Pizza'
}, {
'id': 4,
'parent_id': null,
'name': 'Burgers'
}, {
'id': 7,
'parent_id': null,
'name': 'Pasta'
}];
$scope.secondaryFoods = [
{
'id': 2,
'parent_id': 1,
'name': 'Cheese Pizza'
}, {
'id': 3,
'parent_id': 1,
'name': 'Combo Pizza'
}, {
'id': 5,
'parent_id': 4,
'name': 'Cheese Burgers'
}, {
'id': 6,
'parent_id': 4,
'name': 'Hamburgers'
}, ];
});
app.directive('doubleTagManager', function() {
return {
restrict: 'E',
scope: {
tags: '=',
primary: '=',
secondary: '=',
userPrimary: '=',
userSecondary: '=',
sub_cat_show: '=',
'all_sub_cat_show': '='
},
template: "<div class='row'><div class='col-md-6'><select ng-change='primaryChange()' name='uFoodsPrimary' id='foodPrimary' class='form-control' ng-model='userPrimary' ng-options='item.name for item in primary track by item.name' required> <option value=''>Select a Food category!</option></select></div><div ng-show='sub_cat_show' class='col-md-6'><select ng-show='all_sub_cat_show' ng-change='secondaryChange()' name='uFoodsSecondary' id='foodSecondary' class='form-control' ng-model='userSecondary'" +
//options code
"ng-options='item.name for item in (secondary | filter: {parent_id: userPrimary.id}) track by item.name' required>" +
//end options code
"<option value=''>Select a Food sub-category!</option></select> <select ng-show='!all_sub_cat_show'><option value=''>Food all sub-category</option></select> </div></div><div><a ng-repeat='(idx, tag) in tags' class='tag' ng-click='remove(idx)'>{{tag}}</a></div>",
link: function($scope, $element) {
var primarySel = angular.element($element.find('select')[0]);
var secondarySel = angular.element($element.find('select')[1]);
// This adds the new tag to the tags array in '<Primary>: <Secondary>' format
$scope.primaryChange = function() {
$scope.tags = []; // reset
$scope.sub_cat_show = primarySel[0].value?true:false;
if (primarySel[0].value == 'All Foods')
{
$scope.all_sub_cat_show = false;
angular.forEach($scope.primary, function(primary, index) {
angular.forEach($scope.secondary, function(secondary, index) {
if(secondary.parent_id==primary.id)
$scope.tags.push(primary.name + ': ' + secondary.name);
});
});
}
else
{
$scope.all_sub_cat_show = true;
}
}
$scope.secondaryChange = function() {
var new_value = secondarySel[0].value;
if ($scope.tags.indexOf(new_value) < 0) {
$scope.tags.push(primarySel[0].value + ': ' + new_value);
}
};
// This is the ng-click handler to remove an item
$scope.remove = function(idx) {
$scope.tags.splice(idx, 1);
};
}
};
});
<script src="https://code.angularjs.org/1.4.3/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title>AngularJS Demo</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<double-tag-manager tags="tags" primary="primaryFoods" secondary="secondaryFoods" user-primary="userCategory" user-secondary="userFood">
</double-tag-manager>
</div>
</body>
</html>
After looking more into stack overflow the best (and perhaps only) solution was to chain another filter that would clone the filtered array and unshift another option.
The new filter:
app.filter('addAll', function () {
return function(input) {
// clone the array, or you'll end up with a new "None" option added to your "values"
// array on every digest cycle.
var newArray = input.slice(0);
newArray.unshift({name: "All Foods"});
return newArray;
};
});
Updated ng-options tag:
ng-options="item.name for item in (secondary | filter: {parent_id: userPrimary.id} | addAll)
track by item.name"
SO post
Updated Fiddle
Have a basic angular app,
HTML
<input type="text" ng-model="txt.name" />
<ul>
<li ng-repeat="d in data | filter: txt:strict">
<span>{{d.name}}</span>
<br />
<span>{{d.description}}</span>
<br />
<span>{{d.loremipsum}}</span>
<br />
</li>
</ul>
JS:
var app = angular.module('app', []);
app.controller("mc", function($scope){
$scope.data = [{
'name': 'asd',
'description': 'jiocioasdiasidjpoasdko',
'loremipsum': 'loremipsum'
}, {
'name': 'qwe',
'description': 'poqwpeqwpe',
'loremipsum': 'loremipsum'
}, {
'name': 'czxc',
'description': 'asdasdasd',
'loremipsum': 'loremipsum'
}]
});
I want to be able to search by both name and description, but not by loremipsum
How can I do this?
Example on JS BIN
You can create your custom filter please see demo below
var app = angular.module('app', []);
app.controller("mc", function($scope) {
$scope.data = [{
'name': 'asd',
'description': 'jiocioasdiasidjpoasdko',
'loremipsum': 'loremipsum'
}, {
'name': 'qwe',
'description': 'poqwpeqwpe',
'loremipsum': 'loremipsum'
}, {
'name': 'czxc',
'description': 'asdasdasd',
'loremipsum': 'loremipsum'
}];
});
app.filter('customFilter', function() {
return function(items, string) {
var filtered = [];
var stringMatch = new RegExp(string, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (stringMatch.test(item.name) || stringMatch.test(item.description)) {
filtered.push(item);
}
}
return filtered;
};
});
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="mc">
<input type="text" ng-model="txt.name" />
<ul>
<li ng-repeat="d in data | customFilter: txt.name">
<span>{{d.name}}</span>
<br />
<span>{{d.description}}</span>
<br />
<span>{{d.loremipsum}}</span>
<br />
</li>
</ul>
</body>
</html>
Here's an example using a custom function:
custom function solution
You will probably want to use match instead of === in the custom function.