Reputation: 3393
i am trying to display element only if the uid
exist in JSON array:
i've tried it so far:
var app = agular.module('myApp', []);
app.controller('myCtrl', function () {
$scope.uid = '10';
$scope.datas = [{
'id': '1',
'name': 'abc'
}, {
'id': '2',
'name': 'xyz'
}];
});
<p ng-if="datas.length | filter:{id: uid}">ID exist in array</p>
Upvotes: 2
Views: 6226
Reputation: 1786
you can define function on scope that would that for u (and use filter service inside)
i.e.
<div ng-app="mod">
<div ng-controller='MCtrl'>
<p ng-show="exists(1)">ID exist in array</p>
</div>
</div>
mod.controller('MCtrl', function($scope, $filter){
var items = [123,2,1]
$scope.exists = function(val){
return $filter('filter')(items, val).length > 0;;;
}
});
if you'd like to do it in view
<p ng-show="(items|filter:1:true).length > 0">ID exist in array</p>
btw, true means it should be exact match
Upvotes: 5
Reputation: 16498
Hi please see here: fiddle
<div ng-app="app">
<div ng-controller="myCtrl">
<p ng-show="check()">ID exist in array</p>
<p ng-hide="check()">ID NOT exist in array</p>
</div>
</div>
JS:
var app = angular.module('app', []);
app.controller('myCtrl', function ($scope) {
$scope.uid = '2';
$scope.datas = [{
'id': '1',
'name': 'abc'
}, {
'id': '2',
'name': 'xyz'
}];
$scope.check = function () {
var ifExist = false;
angular.forEach($scope.datas, function (data) {
if (data.id == $scope.uid)
ifExist = true;
});
return ifExist;
}
});
Upvotes: 4