Searching a map and retrieving key if matching -angular js - angularjs

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

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>

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>

Related

Getting the value of ng-model input from controller angular js

I'm trying to get the value of my ng-model input to my controller. The input value has a value and not empty.
Why this code is not working? It says undefined when you alert or console log. What did i missed? really appreciate your help. here is my code
input --> the value is 1
<input type="text" name="idval" ng-model="Data.idval">
js
app.controller('Controller', function($scope, $http){
$scope.fetchvalue = function(){
var id = $scope.Data.idval; // not working
var id = $scope.idval; // even this one
alert(id); // its undefined
$http.post(
"query.php", {
'ID': id,
}
).then(function(response) {
console.log(response.data);
});
}});
Here is a working solution for your code:
You need to declare an object and bind it to ng-model,
$scope.Data = {};
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.Data = {};
$scope.fetchvalue = function(){
var id = $scope.Data.idval; // not working
alert(id); // its undefined
}
});
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form novalidate>
<input type="text" name="idval" ng-model="Data.idval">
<button ng-click="fetchvalue()">Submit</button>
</form>
</div>
</body>
</html>
Here is a working Plunker
I understand,
see you defined id twice, first id get the value from ng-model which must be assigning ng-model value to id variable and you override id with undefined variable called idval.
You can either remove line var id = $scope.idval; or
modify alert(id); as alert($scope.Data.idval)
You need to declare it somewhere before you use it.
$scope.DATA = ""
var id = $scope.Data.idval;
Try this out

Append key value pair to angularjs object

I am getting json output from laravel 5.2 form request validation
My json output is:
{
"title": [
"The title field is required."
],
"description": [
"The description field is required."
],
"address.city": [
"City field is required"
]
}
Appending this output to object
var self = this;
self.error = {
address: {}
};
var onFailure = function (response) {
angular.forEach(response.data, function(value, key) {
self.error[key] = value[0];
});
};
I want to access this error object to my view, for "address.city", I can't access it using "ctrl.error.address.city", rest I can access
How to append object with key containing "." and show it in view?
Here is what you need. But its better not to have (.) in a property name. Instead you can use a underscore(_). Avoid using dot(.) as a chaaracter in property names.
var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo['hello.There'] = "I'm foo!";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
{{foo["hello.There"]}}<br />
<input type="text" ng-model="foo['hello.There']" />
</div>
if you know the key name then the only way you can access it is by [].
Check the fiddle for more info.
https://jsfiddle.net/9f4mbh1h/1/
You need to change your code to this
in your controller
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo "hi";
});
in html
<div ng-app="MyApp" ng-controller="MyCtrl">
<input type="text" ng-model="foo" /> </div>

Angularjs filter part of name

I have a jsFiddle here - http://jsfiddle.net/GRw64/
I'm new to Angularjs so still finding my feet
My example is a simple ng-init of customer names.
An input field and a ng-repeat to filter the name in the input field against the customer names.
If you type a name in the input field the ng-repeat filters the list to show that name.
If I type Chris the name 'Chris Dave' and 'Chris' appear in the list.
If I change to 'Chris Dave', 'Chris Dave' is still showing in the list but 'Chris' disappears
How can I get a return with all the results that match at least one word in the search.
<!doctype html>
<html ng-app>
<head>
<script src="http://code.angularjs.org/1.2.6/angular.min.js"></script>
</head>
<body ng-app="" data-ng-init="customers=[{name:'Chris Dave'},{name:'Chris'},{name:'John'},{name:'Paul'}]">
<div class="container">
Names:
<br />
<input type="text" data-ng-model="name" />
<br />
<ul>
<li data-ng-repeat="cust in customers | filter:name">{{ cust.name }}</li>
</ul>
</div>
</body>
</html>
You can also provide a function to the filter filter of Angular:
ng-repeat="cust in customers | filter:filterByName"
Then you have to define the function in your controller:
$scope.filterByName = function(customer) {
if(!$scope.name) {
return true;
} else {
var keywords = $scope.name.toLowerCase().split(' ');
for(var i in keywords){
var k = keywords[i];
if (customer.name.toLowerCase().indexOf(k) >= 0) {
return true;
}
}
return false;
}
}
Working example
Suppose you treat the space-separated keywords as OR relationship, you can create a custom filter to achieve what you need like this:
var app = angular.module('myApp', []);
app.filter('myFilter', function () {
return function (names, keyword) {
var listToReturn = [];
if (keyword === undefined) return names;
var keywords = keyword.toLowerCase().split(' ');
angular.forEach(names, function (name) {
for(var i in keywords){
var k = keywords[i];
if (name.name.toLowerCase().indexOf(k) >= 0) {
listToReturn.push(name);
break;
}
}
});
return listToReturn;
};
});
DEMO

ng-options displays blank selected option, even though ng-model is defined

I have created a plunkr to emphasize the problem, perhaps it's because the source of the ng-repeat is a function, I am not sure, but so far I've tried everything in order to solve this, and couldn't mange.
plunkr:
http://plnkr.co/edit/qQFsRM?p=preview
HTML
<html>
<head>
<script data-require="angular.js#1.2.0-rc1" data-semver="1.2.0-rc1" src="http://code.angularjs.org/1.2.0rc1/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='myApp' ng-controller='mainCtrl'>
<ng-include src="'menu.html'">
</ng-include>
</html>
Script
var app = angular.module('myApp', []);
app.controller('mainCtrl', function($scope, $httpBackend){
$scope.model = {};
$scope.model.myJobs = {};
$scope.refreshJobs = function(){
}
});
app.controller('menuCtrl', function($scope){
$scope.model.locations = function(){
var loc = [];
loc[1] = 'Dublin';
loc[2] = 'Stockholm';
loc[3] = 'New Jersy';
$scope.model.selectedLocationDef = loc.indexOf('Dublin');
return loc;
}
$scope.model.selectedLocation = $scope.model.selectedLocationDef;
$scope.$watch('model.selectedLocation', function(location){
$scope.refreshJobs(location);
});
});
If you use an array as model, then the model is a string not a number. So you need to convert the number to string. Just try
$scope.model.selectedLocation = '1';
Last I checked, Angular does not support the ability to bind array keys to ng-model via ng-options. You can, however, mimic this behavior using an object hash:
menu.html:
<div ng-controller="menuCtrl">
<select ng-model="model.selectedLocation" ng-options="x.value as x.label for x in model.locations()">
</select>
</div>
script.js:
$scope.model.locations = function(){
var loc = [{
value: 0,
label: 'Dublin'
}, {
value: 1,
label: 'Stockholm'
}, {
value: 2,
label: 'New Jersey'
}];
$scope.model.selectedLocation = 1; // Set default value
return loc;
}
Bear in mind that this will bind the integers to your model, and not the cities themselves. If you want your model value to be Dublin, Stockholm, or New Jersey, simply do:
menu.html:
<div ng-controller="menuCtrl">
<select ng-model="model.selectedLocation" ng-options="name for name in model.locations()">
</select>
</div>
script.js:
$scope.model.locations = function(){
var loc = ['Dublin', 'Stockholm', 'New Jersey'];
$scope.model.selectedLocation = 'Dublin'; // Set default value
return loc;
}

How to use checkboxes for creating an array-list of related objects in angularjs

I have a given array of objects, whose objects I would like to add to a 'selected'-list depending on related checkboxes. How could I set them up without having to set up the controller to much.
Here is the fiddle which works fine, when using radio-boxes instead:
http://jsfiddle.net/JohannesJo/6ru2R/
JavaScript:
app = angular.module('app',[]);
app.controller('controller', function($scope){
$scope.aData = [
{i:1},
{i:2}
];
$scope.aSelected = [];
});
html:
<body ng-app="app">
<div ng-controller='controller'>
<input type = "checkbox" ng-model = "aSelected" value = "{{aData[0]}}">
<input type = "checkbox" ng-model = "aSelected" value = "{{aData[1]}}">
<div>test: {{oSelected}}</div>
</div>
</body>
One option is to watch for changes on the oSelected Array and create the list of related objects base on it.
$scope.$watch(function () {
return $scope.oSelected;
}, function (value) {
$scope.selectedItems = [];
angular.forEach($scope.oSelected, function (v, k) {
v && $scope.selectedItems.push($scope.aData[k]);
});
}, true);
jsfiddle: http://jsfiddle.net/bmleite/zea7g/2/

Resources