我只是在JSON数组中存在uid
时才尝试显示元素:
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>
答案 0 :(得分:5)
您可以在范围内定义与u(并在其中使用过滤器服务)
的范围内的函数即
<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;;;
}
});
如果您想在视图中执行此操作
<p ng-show="(items|filter:1:true).length > 0">ID exist in array</p>
btw,true表示它应该完全匹配
答案 1 :(得分:4)
嗨,请看这里: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;
}
});