AngularJs, Search one array against another -
so have 2 arrays, 1 looks little liek this
$scope.users = {id: 1, email: xxx} {id: 2, email: xxx}....
and have one
$scope.booking = {id: 20, regid: 2} ....
so users being displayed in table @ moment.
however if user has booking, want table row have red flag against (cant share table basic ng-repeat) if usersid exists regid in booking array, push user
any wicked
first of $scope.users
, $scope.booking
objects not arrays...
i make example how know if users has book, heres code , plnkr
the magic in foreach , loops.
html
<!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 data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script> <script src="app.js"></script> </head> <body ng-controller="mainctrl"> <table> <thead> <th>id</th> <th>name</th> <th>has book</th> </thead> <tbody> <tr ng-repeat="user in users"> <td>{{user.id}}</td> <td>{{user.name}}</td> <td>{{user.hasbook}}</td> </tr> </tbody> </table> </body> </html>
controller
var app = angular.module('plunker', []); app.controller('mainctrl', function($scope) { $scope.name = 'world'; $scope.users = [ {id:1, name:'john'}, {id:2, name:'barney'}, {id:3, name:'moroni'}, {id:4, name:'adam'}, {id:5, name:'sam'} ]; $scope.books = [ {id:1, regid:1, name:'book1'}, {id:2, regid:2, name:'book1'}, {id:5, regid:3, name:'book1'}, ]; angular.foreach($scope.users, function(value, index){ for(var =0; i< $scope.books.length; i++){ if(value.id === $scope.books[i].id){ value.hasbook = true; } } }); console.log($scope.users); });
Comments
Post a Comment