AngularJS - JSON and return all results - angularjs

I'm trying to write a basic search function using AngularJS. I have written a service that finds my JSON file and binds it to a $scope object $scope.SearchResult
What i am trying to do it perform a search on the items within SearchResult when the user enters a string. For any matches found,return the entire contents.
HTML:
<div ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<input ng-model="searchText">
<button ng-click="performSearch(searchText)">Submit</button>
{{ item }}
</div>
JS:
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.SearchResult = [
{
"Index":1,
"Title":"Help",
"Snippet":"You found Mr Happy",
"Url":"www.test.co.uk"
},
{
"Index":2,
"Title":"Conatct",
"Snippet":"You found Mr Happy",
"Url":"www.test.co.uk"
},
{
"Index":3,
"Title":"Help",
"Snippet":"You found Mrs Angry",
"Url":"www.test.co.uk"
},
{
"Index":4,
"Title":"Help",
"Snippet":"You found Mr Sad",
"Url":"www.test.co.uk"
}
];
$scope.performSearch = function(searchText) {
console.log("Performing a search....");
angular.forEach($scope.SearchResult.Snippet, function(item) {
if( item.label.indexOf(searchText) >= 0 ) filtered.push(item);
console.log(item);
});
}
});
So if HAPPY was entered in the input field, 2 matches would be found and displayed.
Heres a plunker: http://plnkr.co/edit/mOjcYUbFpoveaDw12NjE?p=preview

Related

Store the value of selection from dropdown to a variable AngularJS

I would like to store the value of a selection from a dropdown in AngularJS.
I am able to replicate the new selection on UI but not in console.
<div ng-controller="MyCtrl">
<div>
Fruit List:
<select id="fruitsList"
ng-model="cart"
ng-change="getSelectedLocation()"
ng-options="state for state in shelf"></select>
<br/>
<tt>Fruit selected: {{cart}}</tt>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.cart = "";
$scope.shelf = ['Banana', 'Apple', 'Pineapple', 'Blueberry'];
$scope.getSelectedLocation = function() {
console.log($scope.cart);
}
$scope.printSelectedValue = function() {
if ($scope.cart == 'Banana') {
console.log("Its a banana")
} else if ($scope.cart == "Apple") {
console.log("Its an apple")
} else {
console.log("Its neither a banana nor an apple")
}
}
});
Any idea on how to achieve that?
jsfiddle link
You're printing the cart once, when the controller is instanciated. At that time, the user hasn't had the chance to select anything yet.
If you want to print the selection every time it changes, use ng-change (you're already using it, BTW):
ng-change="printSelection()"
and in the controller:
$scope.printSelection = function() {
console.log($scope.cart);
};

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>

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

Not able to load $http.get - JSON data in ui tabset child tabs

I tried to load a dropdown with the response got from http post. But its failing to load on child tabs.
When i click next button from tab1. I make a post call and get a JSON back. Using the returned data i want to load a dropdown in my second tab.
I already raised a query on tabset and it worked fine. Now I modified the plunker little bit. I did the same way mentioned in the below link. But i'm missing something when i try to do the samething with $http.get
Tabset $rootScope scope not updating
app.js
angular.module('plunker', ['ui.bootstrap'])
.service('Common', function() {
this.tabData = {};
})
.controller('SampleController', function($scope, $http, Common) {
$scope.submitTab1 = function() {
$http.get("post.json", {
// Some logic
}).success(function(data) {
Common.tabData = data;
$scope.steps.step2 = true;
});
}
})
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common.tabData;
});
Html
<tabset ng-init="steps={step1:true, step2:false}">
<tab heading="Step 1" active="steps.step1">
<div data-ng-controller="SampleController">
<form data-ng-submit="submitTab1()">
<label>Some Operations ...</label>
<br>
<br>
<label>Click next to retrieve json from server ...</label>
<button type="submit">Click Next</button>
</form>
</div>
</tab>
<tab heading="Step 2" active="steps.step2">
<div data-ng-controller="SampleTab2Controller">
<form name="step2">
<p>load the json list from Tab1 controller </p>
<select ng-model="selectedUser" ng-options="user.title for user in userList">
<option value="">--- select ---</option>
</select>
</form>
</div>
</tab>
</tabset>
Post.json
[
{
"id": 1,
"title": "Arnold"
},
{
"id": 2,
"title": "stallone"
}
]
Plunker Code http://plnkr.co/edit/EZC1d6tDDZlpWZUHY6os?p=preview
Your issue has nothing to do with loading from http, but it has to do with properly copying reference of objects.
When you do $scope.userList = Common.tabData; the reference of tabData is copied to userList, and then when the tabData is updated using Common.tabData = data now tabData in the service points to a different reference and $scope.userList keeps pointing to the old one. So instead of getting the reference of tabData and copying it to the userList, set up the service object itself on the scope.
In your controller change $scope.userList = Common.tabData to $scope.userList = Common :-
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common;
});
and in the view iterate upon userList.tabData
<select ng-model="selectedUser" ng-options="user.title for user in userList.tabData">
Plnkr
If I modified your code this way it works
1) changed tabData to be an array
2) Used angular.copy instead of asignning
.service('Common', function() {
this.tabData = []; ==> Changed this to array
})
$http.get("post.json", {
// Some logic
}).success(function(data) {
angular.copy(data,Common.tabData); ==> Used angular copy so it copies the array
$scope.steps.step2 = true;
});
Updated Plnkr
main issue in your code is controller get executed first and then Common.tabData is loaded.so can do like this:
angular.module('plunker', ['ui.bootstrap'])
.service('Common', function() {
this.tabData = {};
})
.controller('SampleController', function($scope,$http, Common) {
$scope.submitTab1 = function() {
$http.get("post.json", {
// Some logic
}).success(function(data) {
Common.tabData = data;
$scope.steps.step2 = true;
});
}
})
.controller("SampleTab2Controller", function($scope, Common) {
$scope.userList = Common;
});
and html code according to this is:
<div data-ng-controller="SampleTab2Controller">
<form name="step2">
<p>load the json list from Tab1 controller </p>
<select ng-model="selectedUser" ng-options="user.title for user in userList.tabData">
<option value="">--- select ---</option>
</select>
</form>
</div>

AngularJS - Is there an easy way to set a variable on "sibling" scopes?

I have this problem where I am trying to make a click on a div hide all the other divs of the same "kind". Basically I'd have to, from a child scope set the variable on all other "sibling" scopes.
To illustrate this, I have created the following:
HTML
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-repeat="model in models" ng-controller="MyChildCtrl">
<a ng-click="toggleVisibility()">toggle {{ model.name }} {{ visibility }}</a>
<div ng-show="visibility">
{{ model.name }}
</div>
</div>
</div>
</div>​
JavaScript
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
console.debug('scope');
$scope.models = [
{ name: 'Felipe', age: 30 },
{ name: 'Fernanda', age: 28 },
{ name: 'Anderson', age: 18 }
];
}
function MyChildCtrl($scope) {
$scope.visibility = false;
$scope.toggleVisibility = function() {
$scope.visibility = !$scope.visibility;
}
}
JSFiddle: http://jsfiddle.net/fcoury/sxAxh/4/
I'd like that, every time I show one of the divs, that all other divs would close, except the clicked one.
Any ideas?
#kolrie while your approach works I would suggest a different solution which doesn't require any changes to the model. The basic idea is to keep a reference to a selected item and calculate viability by comparing a current item (inside ng-repeat) with a selected one.
Using this solution the toggle function would become:
$scope.toggleVisibility = function(model) {
$scope.selected = model;
};
and calculating visibility is as simple as:
$scope.isVisible = function(model) {
return $scope.selected === model;
};
Finally the relevant part of the markup is to be modified as follows:
<div ng-controller="MyCtrl">
<div ng-repeat="model in models">
<a ng-click="toggleVisibility(model)">toggle {{ model.name }} {{ isVisible(model) }}</a>
<div ng-show="isVisible(model)">
{{ model.name }}
</div>
</div>
</div>
Here is a complete jsFiddle: http://jsfiddle.net/XfsPp/
In this solution you can keep your model untouched (important if you want to persist it back easily) and have AngularJS do all the heavy-lifting.
OK, I have added a visible attribute to the model, and I managed to get this done:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
console.debug('scope');
$scope.models = [
{ name: 'Felipe', age: 30, visible: false },
{ name: 'Fernanda', age: 28, visible: false },
{ name: 'Anderson', age: 18, visible: false }
];
}
function MyChildCtrl($scope) {
$scope.toggleVisibility = function() {
angular.forEach($scope.models, function(model) {
model.visible = false;
});
$scope.model.visible = true;
}
}
Live here: http://jsfiddle.net/fcoury/sxAxh/5/
Is this the most efficient way? Do you think it's a good practice if I inject this visible attribute into my model data after getting it via AJAX?

Resources