angular ng-options complex json array - javascript

im trying to make a small search engine, using angular and a json object.
im sorting the querys with 3 drop down lists chained so that they populate them selves depending on the selection.
the structure is so: a json object that holds an array of categorys, each category holds an array of products, and each products array hold parameters such as price, name, etc. so when a user selects a category, the second drop down list gets populated with the relevant products. and when the user selects the relevant product the third drop down list gets populated with this products price.
here is the json:
[{
"caregory": "Electronics",
"products": [{
"product": "PC",
"description": "Item4 Product Page",
"price": 99.99
},
{
"product": "PC",
"description": "Item4 Product Page",
"price": 2999.99
},{
"product": "TV",
"description": "lorem ipsum possum",
"price": 250.00
}]
}, {
"caregory": "Home Design",
"products": [{
"product": "Paintings",
"description": "awesome description about anything",
"price": 200.00
}, {
"product": "Pencils",
"description": "we are filters",
"price": 29.99
}, {
"product": "Sharpies",
"description": "loremloremlorem",
"price": 89.00
}
]
}]
here is the js:
var app = angular.module('app', ['angular.filter']);
var Controller = function($scope,$http) {
$http.get('data.json')
.success(function(data) {
$scope.data = data;
});
var data;
$scope.selected = {};
$scope.data = $scope.data;
console.log($scope.data);
var self = this;
$scope.search = function(predicate)
{
$scope.searchPredicate = predicate;
}
}
app.controller('ctrl', Controller);
and here is the view:
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css" />
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="filters.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="ctrl">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div class="jumbotron">
<h1>Search engine</h1>
</div>
<form>
<div class="form-group">
<label for="caregory">Category</label>
<select id="caregory" data-ng-model="selected.category" ng-options="option as option.caregory for option in data | orderBy:'caregory'">
<option value="">None</option>
</select>
<br />
<br />
<label for="filters">Product type</label>
<select id="filters" ng-model="selected.type" ng-options="option as option.product for option in selected.category.products | unique: 'product'">
<option value="">None</option>
</select>
<br>
<br>
<label for="filters">Price</label>
<select id="filters" ng-model="selected.price" ng-options="option as option.price for option in selected.category.products | unique: 'price'">
<option value="">None</option>
</select>
</div>
<div class="form-group" ng-if="selected.price">
<button class="btn btn-primary" ng-click="search(selected.price)">Search</button>
</div>
<div ng-if="searchPredicate">
Searching for <b>{{searchPredicate.product}}</b> in <b>{{searchPredicate.description}}</b> with price <b>{{searchPredicate.price | currency}}</b>
</div>
</form>
</body>
</html>
heres a plunker:
http://plnkr.co/edit/omLQMQa39TRVMXovRKcD?p=preview
thanks!

You need to apply a filter on third select, to filter only products equals to selected:
<select id="filters"
ng-model="selected.price"
ng-options="option as option.price for option in selected.category.products | filter: { product: selected.type.product } | unique: 'price'">
<option value="">None</option>
</select>
take a look at plunker

Related

How to filter array with arraylist using ng-repeat

I'm trying to filter an array with a simple array list but I can't seem to figure out how, I tried using a custom filter but I can't make it work.
Edit: I've added more code. Text box Search works fine but when I add the myFilterby on the ng-repeat it no longer filters. I simply want to filter out an array list.
<div class="input-group">
<input type="text" class="form-control" placeholder="Search .." ng-model="searchText">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
<td ng-repeat="a in product| filter:searchText | filter:myFilterBy">
<img class="avatar" src="img/{{a.image}}" alt="">
<div class="middleT">
<p>{{a.brand}} {{a.model}} </p>
<p>${{a.price}} </p>
</div>
Angular:
var HandleModule = angular.module("HandleModule",['rzModule','ui.bootstrap','angular.filter']);
HandleModule.controller('HandleCtrl',function($scope,$http){
// get data from the server in JSON format
$scope.chk0 = ['apple', 'orange', 'banana'];
$http.get('./loader.php').then(successCallback, errorCallback);
function successCallback(response){
//success code
$scope.product = response.data;
}
function errorCallback(error){
//error code
$scope.product="error";
}
$scope.myFilterBy = function(e) {
return $scope.chk0.indexOf(e) !== -1;
}
PHP:
<?php
$con = mysqli_connect("localhost","root","","product");
$query = "SELECT id, model, brand, price, description, image, FROM fruits ORDER BY id";
$result = mysqli_query($con, $query);
$fruits= array();
while($row = mysqli_fetch_assoc($result))
{
$fruits[] = $row;
}
echo json_encode($fruits);
?>
Used NG-repeat to print out the data separately. I used ng-repeat to display on html
<p ng-repeat="a in products ">
{{a}}
{"id":"1","model":"test1","brand":"orange","price":"4",
"description":"orange sweet and sour","image":"orange.jpg"}
{"id":"2","model":"test2","brand":"banana","price":"3",
"description":"yellow sweet","image":"banana.jpg"}
{"id":"3","model":"test3","brand":"apple","price":"5",
"description":" red sweet crunchy","image":"apple.jpg"}
From what I can decipher from your question and subsequent comments, you are simply trying to filter your product array by search text that is input by the user and a static array.
Your issue is that you are trying to compare an object to an array of strings. To fix your problem you should compare an object property, in this case brand, against the array of strings.
You can see it working below. For simplicity I have removed any code that wasn't essential to this issue.
var HandleModule = angular.module("HandleModule", []);
HandleModule.controller('HandleCtrl', function($scope) {
$scope.chk0 = ['apple', 'orange', 'banana'];
$scope.product = [{
"id": "1",
"model": "test1",
"brand": "orange",
"price": "4",
"description": "orange sweet and sour",
"image": "orange.jpg"
}, {
"id": "2",
"model": "test2",
"brand": "banana",
"price": "3",
"description": "yellow sweet",
"image": "banana.jpg"
}, {
"id": "3",
"model": "test3",
"brand": "apple",
"price": "5",
"description": "red sweet crunchy",
"image": "apple.jpg"
}, {
"id": "4",
"model": "test4",
"brand": "pear",
"price": "6",
"description": "red sweet crunchy",
"image": "pear.jpg"
}];
$scope.myFilterBy = function(e) {
return $scope.chk0.indexOf(e.brand) >= 0;
};
});
<html ng-app="HandleModule">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller="HandleCtrl">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search .." ng-model="searchText" />
</div>
<table>
<tbody>
<tr>
<td ng-repeat="a in product| filter:searchText | filter:myFilterBy">
<div>
<p>{{a.brand}} {{a.model}} </p>
<p>${{a.price}} </p>
</div>
</td>
</tr>
</tbody>
</table>
</body>
</html>

AngularJS default dropdown select not working

var jsonData ='[
{"type":"product",
"id":1,"label":"Color",
"placeholder":"Select Jean Color",
"description":"",
"defaultValue":"Brown",
"choices":[{
"text":"Denim",
"price":"$0.00",
"isSelected":"false"
},
{
"text":"Black",
"price":"$0.00",
"isSelected":"true"
},
{
"text":"Brown",
"price":"$0.00",
"isSelected":"false"
}],
"conditionalLogic":
{
"actionType":"show",
"logicType":"all",
"checkbox":true,
"rules":[{
"fieldId":2,
"operator":"or",
"value":"Regular"
},
{
"fieldId":3,
"operator":"or",
"value":"Low"
}]
}},
{
"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"Color Descrioton","defaultValue":"Red","choices":[{"text":"Red","price":"200","isSelected":"true"}],"conditionalLogic":""},{"type":"product","id":3,"label":"Select Fit","placeholder":"Select Jean Fit","description":"","defaultValue":"Fit","choices":[{"text":"Regular","price":"$0.00","isSelected":"false"},{"text":"Skinny","price":"$10.00","isSelected":"false"},{"text":"Fit","price":"$5.00","isSelected":"false"}],"conditionalLogic":{"actionType":"show","logicType":"all","checkbox":true}},{"type":"product","id":4,"label":"Select Rise","placeholder":"Select Rise","description":"","defaultValue":"Low","choices":[{"text":"High","price":"$29.00","isSelected":"false"},{"text":"Low","price":"$0.00","isSelected":"true"}],"conditionalLogic":""},{"type":"product","id":5,"label":"Size","placeholder":"Select Size","description":"","defaultValue":"Size 36","choices":[{"text":"Size 30","price":"100.00","isSelected":"false"},{"text":"Size 32","price":"100.00","isSelected":"true"},{"text":"Size 34","price":"100.00","isSelected":"true"},{"text":"Size 36","price":"100.00","isSelected":"false"}],"conditionalLogic":""}]';
$scope.attributes = jsonData;
HTML
<div class="col-sm-6" ng-repeat="product_attribute in attributes">
<div class=" form-group">
<label class="font-noraml">{{product_attribute.label}}</label>
<select class="form-control m-b" name="option_choices" ng-selected="option.isSelected=='true'" ng-model="option.price" ng-options="option.price as option.text for option in product_attribute.choices">
<option value="">{{product_attribute.placeholder}}</option>
</select>
</div>
</div>
Above I have posted my JSON and HTML code. I want to show all the attributes choices in my dropdown with default selected value. Please check my HTML I have tried ng-selected="option.isSelected=='true'" to default select my choices options. But that is not working.
Screenshot:
You must have defaultValue as object that comprising all properties.Here is your solution ->
jsfiddle
For example:
"defaultValue": {
"text": "Black",
"price": "$0.00",
"isSelected": "true"
}

How can I get cascading dropdown at level 4?

Here is my attempt:
If the user hits Territory A i need to display "Sales Team A" and "Sales Team B" as my options.`enter code here: http://plnkr.co/edit/n2A83tHk4r0G1ZWddb7V?p=preview.
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div data-ng-app="myApp" class="container">
<form class="form-horizontal" data-ng-controller="dropdownCtrl">
<div class="form-group">
<label for="country" class="col-sm-2 control-label">* </label>
<div class="col-sm-7">
<select data-ng-model="customer.Country"
data-ng-options="obj.id as obj.country for obj in countries"
data-ng-change="getCountryStates()"
class="form-control"
data-ng-required="true"
id="country">
<option value="">-- Choose Org --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="state" class="col-sm-2 control-label">** </label>
<div class="col-sm-7">
<select data-ng-model="customer.State"
data-ng-options="x.Id as x.state for x in sates"
data-ng-change = "getStateCities()"
class="form-control"
data-ng-required="true"
id="state">
<option value="">-- Select --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="city" class="col-sm-2 control-label">*** </label>
<div class="col-sm-7">
<select data-ng-model="customer.City"
data-ng-options="x.Id as x.city for x in cities"
data-ng-change = "getStatesSales()"
class="form-control"
data-ng-required="true"
id="city">
<option value="">-- Select --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="sales" class="col-sm-2 control-label">**** </label>
<div class="col-sm-7">
<select data-ng-model="customer.Sales"
data-ng-options="x.Id as x.sales for x in mysales"
class="form-control"
data-ng-required="true"
id="sales">
<option value="">-- Select --</option>
</select>
</div>
</div>
</form>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Here is my index.js file:
var myApp = angular.module('myApp',[]);
myApp.controller('dropdownCtrl', ['$scope','CustomerService', function($scope, CustomerService) {
$scope.countries = CustomerService.getCountry();
$scope.getCountryStates = function(){
$scope.sates = CustomerService.getCountryState($scope.customer.Country);
$scope.cities =[];
$scope.mysales = [];
}
$scope.getStateCities = function(){
// debugger;
$scope.cities = CustomerService.getStateCity($scope.customer.State);
console.log("Hi");
// console.log($scope.cities);
}
$scope.getStatesSales = function(){
// debugger;
$scope.sales = CustomerService.getSalesList($scope.customer.Sales);
// console.log($scope.sales);
}
}]);
myApp.factory("CustomerService", ['$filter', function($filter){
var service = {};
var countrylist = [
{ "id": 1, "country": "Marketing" },
{ "id": 2, "country": "Sales" },
{ "id": 3, "country": "Customer Service" }
];
var statelist = [
{"Id":1, "state":"Marketing Team A", "countryId": 1},
{"Id":3, "state":"Marketing Team B", "countryId": 1},
{"Id":4, "state":"Territories", "countryId": 2}
];
var citylist = [
{"Id":5, "city":"Territory A", "stateId": 4},
{"Id":6, "city":"Territory B", "stateId": 4}
];
var salesTeamList = [
{"Id":1, "sales":"Sales Team A", "salesId": 5},
{"Id":2, "sales":"Sales Team B", "salesId": 5},
{"Id":3, "sales":"Sales Team A", "salesId": 6},
{"Id":4, "sales":"Sales Team B", "salesId": 6}
];
service.getCountry = function(){
return countrylist;
};
service.getCountryState = function(countryId){
var states = ($filter('filter')(statelist, {countryId: countryId}));
return states;
};
service.getStateCity = function(stateId){
var items = ($filter('filter')(citylist, {stateId: stateId}));
return items;
};
service.getSalesList = function(salesId){
var items = ($filter('filter')(salesTeamList, {salesId: salesId}));
return items;
console.log(items);
};
return service;
}]);
You missed two points:
I changed here the parameter to $scope.customer.City
$scope.getStatesSales = function(){
$scope.sales = CustomerService.getSalesList($scope.customer.City);
}
and in your last drop down you passed the wrong list mySales so I changed it to sales in ng-repeat
data-ng-options="x.Id as x.sales for x in sales"
See the plunker

How do I get all selected dropdown values in one model angular js

<tr ng-show="show">
<td>
<select class="form-control" data-ng-model="MyModel.FirstName" data-ng-options="firstname.Name for name in MyProperties" ng-show="editmode" style="width:100%; ">
<option value="" style="margin-left:25px">-Select First Name-</option>
</select>
</td>
<td>
<select class="form-control" data-ng-model="MyModel.LastName.SelectedOption" ng-options="lastname.Name for lastname in MyModel.LastName.Options" ng-show="editmode" style="width:100%; ">
<option value="" style="margin-left:25px">-Select Last Name-</option>
</select>
</td>
<td>
</td>
How do I get both dropdown (dynamically generated) values in single model which I could pass to save method and get it in index,js
index.js
$scope.Save = function (MyModel) {
var AlldataObj = {
FirstName: MyModel.FirstName,
LastName: MyModel.LasttName
};
Have a look at this code might be useful for you
<doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body ng-app="myApp" data-ng-controller="HomeCtrl">
<select ng-model="opt.first" ng-options="obj.code as obj.code for obj in opts">
<option value="">select</option>
</select>
<select ng-model="opt.second" ng-options= "obj.code as obj.code for obj in opts1">
<option value="">select</option>
</select>
<button ng-click="save(opt)">Save</button>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
angular.module('myApp', []);
angular.module('myApp').controller('HomeCtrl', ['$scope', function($scope) {
$scope.opts = [
{
"code" : "ABC",
"num" : ["246810","4681012","681012"]
},
{
"code" : "DEF",
"num" : ["13579","357913","5791315"]
}
] ;
$scope.opts1 = [
{
"code" : "ABC",
"num" : ["246810","4681012","681012"]
},
{
"code" : "DEF",
"num" : ["13579","357913","5791315"]
}
] ;
$scope.save=function(model)
{
console.log("model==", model)
var obj={};
obj.firstname=model.first;
obj.lastname=model.second;
console.log("first==", obj.firstname);
console.log("last==", obj.lastname)
}
}]);
</script>
</body>
</html>
There seems to be some convolution in your model, which I'm guessing stems form application needs that aren't obvious here. However the main answer to your question, I believe is that you can defined the model in the function as: ng-click="Save(MyModel)" where MyModel is a $scope variable.
HTML
Save
Further more, you can manipulate this information in your save function:
$scope.Save = function(MyModel) {
var values = {
first: MyModel.FirstName,
last: MyModel.LastName.SelectedOption
};
console.log(values);
//Or $http/Restangular post these values somewhere
}
I've created a working Plunkr for your reference here.

AngularJs Directive for crossbrowser SELECT Dropdown

I'm trying to create below Cross-browser dropdown:
Currently this is my HTML:
var myapp = angular.module('myapp', []);
myapp.controller('myCtrl', function($scope) { //temporory stuff
$scope.investments = [{
"name": "AARPOperatingFunds"
}, {
"name": "SomeBigTitle"
}, {
"name": "IhatezIE8"
}, {
"name": "ILoveFFDeveLoperEdition"
}, {
"name": "GiveMeSomeLove"
}];
$scope.investment = $scope.investments[0].name;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
<div ng-app="myapp" ng-controller="myCtrl">
<span class="dropdown">
<i ng-bind="investment" class="before"></i>
<select ng-model="investment">
<option ng-repeat="ip in investments | orderBy:'name' " ng-value="ip.name">{{ ip.name }}</option>
</select>
</span>
</div>
But what I need is, when someone selects the Dropdown, ng-bind will update and also
I do not want to add mg-model each time.
And main thing is if OPTION value is sometime like this "AARPOperatingFunds" it should get displayed as "AARP Operating Funds"
Please guide. Can we create any Directive here for the above purpose.
I need something like this:
<span class="dropdown">
<i class="before" mySelectDirective></i>
<select id="investProgram" ng-options="ip for ip in ips | orderBy:'ip' "></select>
</span>
OR this one:
<span class="dropdown mySelectDirective">
</span>
Use ng-options combined with adding a "label" attribute to your array:
$scope.investments = [{
"name": "AARPOperatingFunds",
"label":"AARP Operating Funds"
}, {
"name": "SomeBigTitle",
"label":"Some Big Title"
}];
Then:
<select ng-model="investment" ng-options="opt.name as opt.label for opt in investments"></select>
https://docs.angularjs.org/api/ng/directive/select

Categories