Alvin Wee Alvin Wee - 5 months ago 14
Javascript Question

Retrieve unqiue value using ng-option with angularJS

My html file:

<html ng-app='camListApp'>
<div ng-controller="Hello">
<h3>Search:</h3><br>
<select ng-model="searchBox" ng-options="x.cameraid as x.cameraid for x in records| unique:'cameraid'">
<option value="">{{x.cameraid}}</option>
</select>


My current js file:

var camListApp = angular.module('camListApp', []);
camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
camListApp.filter('unique', function() {
return function(input, key) {
var unique = {};
var uniqueList = [];
for(var i = 0; i < input.length; i++){
if(typeof unique[input[i][key]] == "undefined"){
unique[input[i][key]] = "";
uniqueList.push(input[i]);
}
}
return uniqueList;
};
});

$scope.custom = true;
$scope.toggleCustom = function() {
$scope.custom = ! $scope.custom;
};

$http.get('http://localhost:8081/camera/list').then(function(response) {
console.log(response);
$scope.records= response.data;
});
}]);


My json data on web service:

[{"id":23,"cameraid":"000000006f4280af","timestamp":"2016/06/15 17:27","filename":"452c5d867b563e937d44d48ebc326c7a"},
{"id":24,"cameraid":"000000006f4280af","timestamp":"2016/06/15 17:27","filename":"ee90428e4e0c19ba9858285398bf4fbb"},
{"id":25,"cameraid":"000000006f4280af","timestamp":"2016/06/15 17:28","filename":"c9a4fb339f6981ffd679937724167de8"},
{"id":26,"cameraid":"000000006f4280af","timestamp":"2016/06/15 17:28","filename":"a1df86417d958e670750cf8172a2b7dd"}


Why i can't display my cameraid unique value "000000006f4280af" on my dropdownlist? I used ng-option to display unique value for my cameraid. Anyone can help me solve this?

Answer

To achieve the expected result,use below option

ng-options -x.cameraid for x in records| unique:'cameraid (syntax is wrong in the post)

          <div ng-app="camListApp" ng-controller="Hello">
      <select ng-model="searchBox" ng-options="x.cameraid as x.cameraid for x in records| unique:'cameraid'">
      <option value="">{{x.cameraid}}</option>
      </select>
      </div>

And create filter in your js file as below

        camListApp.filter('unique', function() {
        return function(input, key) {
            var unique = {};
            var uniqueList = [];
            for(var i = 0; i < input.length; i++){
                if(typeof unique[input[i][key]] == "undefined"){
                    unique[input[i][key]] = "";
                    uniqueList.push(input[i]);
                }
            }
            return uniqueList;
        };
    });

Codepen url - http://codepen.io/nagasai/pen/dXXzLY for reference.

Hope this works for you :)

Comments