Techhub
Techhub

Reputation: 23

Searching a map and retrieving key if matching -angular js

Angular-JS Searching a map and retrieving key if matching with the user given input key

my map luks like this

var myMap= { k:1000, l:100000, m:1000000, c:10000000 }; If user input is "l" , i want to search the map and retrieve l along with value "100000" and do some further operation

Upvotes: 0

Views: 406

Answers (2)

Kaysar
Kaysar

Reputation: 43

To extend the answer from Gruff Bunny, you can also do the following to search for the key-value pair and do your calculation inside the controller and get the result as an output.

angular.module('MyModule', [])

.controller('MyController', function($scope) {

  $scope.myMap = { k:1000, l:100000, m:1000000, c:10000000 };
  $scope.chkIt = function(myIns){
    var myVal = $scope.myMap[myIns];
    if(myVal){
      //do your calculation here
      $scope.myResult = 'Calculation Done | Key: '+myIns+' | Value: '+myVal;
    }else{
      $scope.myResult = 'No Match for key: '+myIns;
    }
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='MyModule' ng-controller='MyController'>
  <input type='text' ng-change="chkIt(myMapKey)" ng-model='myMapKey' />
  <p>myMap value = {{myResult}}</p>
</div>

Upvotes: 0

Gruff Bunny
Gruff Bunny

Reputation: 27976

As myMap is an object (aka associative array, aka hash) you can access a value using the [] operator.

angular.module('MyModule', [])

.controller('MyController', function($scope) {

  $scope.myMap = { k:1000, l:100000, m:1000000, c:10000000 };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='MyModule' ng-controller='MyController'>
  <input type='text' ng-model='myMapKey' />
  <p>myMap value = {{myMap[myMapKey]}}</p>
</div>

Upvotes: 1

Related Questions