2014-06-25 56 views
2

我試圖只有當uid在JSON陣列存在顯示元素:顯示元素只有在JSON數組值匹配

到目前爲止,我已經嘗試過:

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> 

DEMO FIDDLE

回答

5

你可以在範圍上定義這個功能(並在裏面使用過濾服務)

<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> 

順便說一句,真的意味着它應該是精確匹配

+0

是不是可以在VIEW? – Jay

+0

更新了答案,只包括查看解決方案 – marcinn

+0

我試過但沒有工作。如果你可以更新我的小提琴並給我一個生動的例子。 – Jay

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; 

    } 
});