Change value on second select and keep values - javascript

Hello I would like to load data options of the 2nd select from mysql when I click on a value of the first selectors.
And keep the JSON data of the last fields selected and keep append function.
I know how to import data from mysql, but I Would like to get Values each time I change the first selectors without changing all second selectors, only the concerned selector.
How it works.
I select a category ( not shown in the code )
the most important:
The select 1 receive all categories of category selected.
The select 2 receive all categories of select 1 subcategory
when the 1first category is changed, the 2nd selector are loaded but don't forget I need to add unlimited fields without changing all 2nd selectors
im using this code:
https://plnkr.co/edit/kKjhpy0fdnOprFA8PAYx?p=preview
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="appCtrl">
<h3>Add Input fields dynamically</h3>
<button ng-click="addSelectItem()">Add select Field</button>
<div ng-repeat="item in selects">
<select ng-model="item.type"><option ng-repeat='option1 in type' value='{{option1.nomcarac}}' >{{option1.nomcarac}}</option></select>
<select ng-model="item.brandname" ><option ng-repeat='option1 in valuelist' value='{{option1.nomcarac}}' >{{option1.nomcarac}}</option></select>
<button ng-click="getValue(item)">get input value</button>
</div>
<pre>{{inputs | json}}</pre>
<pre>{{selects | json}}</pre>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('appCtrl', function($scope) {
$scope.inputs = [];
$scope.selects = [];
$scope.type = [{nomcarac: "phone"},{nomcarac: "shoes"}]
$scope.phonelist = [{nomcarac: "apple"},{nomcarac: "motorola 10g"}]
$scope.valuelist = [{nomcarac: "test"},{nomcarac: "test2"}]
$scope.shoeslist = [{nomcarac: "jean michel"},{nomcarac: "motorola 10g"}]
var count = 1;
var fieldname;
$scope.addItem = function(){
fieldname = "Field " + count;
$scope.inputs.push({name: fieldname});
count++;
}
$scope.addSelectItem = function(){
fieldname = "Field " + count;
$scope.selects.push({name: fieldname});
count++;
}
$scope.getValue = function(item){
alert(item.value);
}
});
</script>
</body>
</html>

If I understood you correctly, you want to populate options of the second select every time, you change the value of the first select in the group.
If so, you can use ngChange to accomplish this and store the values list within the corresponding item object:
var app = angular.module('myApp', []);
app.controller('appCtrl', function($scope) {
$scope.inputs = [];
$scope.selects = [];
$scope.type = [{nomcarac: "phone"}, {nomcarac: "shoes"}];
$scope.phonelist = [{nomcarac: "apple"}, {nomcarac: "motorola 10g"}];
$scope.shoeslist = [{nomcarac: "jean michel"}, {nomcarac: "gucci"}];
var count = 1;
var fieldname;
$scope.addItem = function(){
fieldname = "Field " + count;
$scope.inputs.push({name: fieldname});
count++;
};
$scope.addSelectItem = function(){
fieldname = "Field " + count;
$scope.selects.push({name: fieldname});
count++;
};
$scope.getValue = function(item){
console.log(item);
};
$scope.getValuesList = function(item) {
//get actual data from db
switch (item.type){
case 'phone':
item.valuelist = angular.copy($scope.phonelist);
break;
case 'shoes':
item.valuelist = angular.copy($scope.shoeslist);
break;
default:
item.valuelist = [];
break;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="appCtrl">
<h3>Add Input fields dynamically</h3>
<button ng-click="addSelectItem()">Add select Field</button>
<div ng-repeat="item in selects">
<select ng-model="item.type" ng-change='getValuesList(item)'>
<option ng-repeat='option in type' value='{{::option.nomcarac}}' >{{::option.nomcarac}}</option>
</select>
<select ng-model="item.brandname">
<option ng-repeat='option in item.valuelist' value='{{::option.nomcarac}}' >{{::option.nomcarac}}</option>
</select>
<button ng-click="getValue(item)">get input value</button>
</div>
<pre>{{inputs | json}}</pre>
<pre>{{selects | json}}</pre>
</div>

Related

ng-repeat Drop-down to restrict selecting same value multiple times

I have a drop-down inside ng-repeat and a add button that can add new drop-down to the list as I've shown in the JSFiddle, and I want to restrict the second drop-down to select the first selected value in the second drop-down. So the value selected in the first drop-down should not allowed to select in the second or hide that value.
In my old question pankaj parkar given the answer,But I am unable to integrate that answer in my JSFiddle.
ng-repeat="post in posts | filter: { type: selectedValue }"
Please help me on this.
This is my old question
My JSFiddle.
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.names = ['Mobile','Office','Home'];
$scope.choices = [{id: 'choice1'}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
$scope.choices.push({'id':'choice'+newItemNo});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset ng-model='y' ng-repeat="choice in choices">
<select>
<option ng-model='x1' ng-repeat = "x in names">{{x}}</option>
</select>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>
Put your options in scope items array. Get your output result from choices array.
var app = angular.module('angularjs-starter', []);
app.filter("itemFilter", function(){
return function(items, choice){
filtered_items=[];
for(var i=0;i<items.length;i++){
if(items[i].choiceID==null || items[i].TYPE_ID==choice.TYPE_ID)
filtered_items.push(items[i]);
}
return filtered_items;
}
});
app.controller('MainCtrl', function($scope) {
$scope.items = [
{"TYPE_ID":1,"TYPE_NAME":"Jpeg"},
{"TYPE_ID":2,"TYPE_NAME":"Odt"},
{"TYPE_ID":3,"TYPE_NAME":"docx"},
{"TYPE_ID":4,"TYPE_NAME":"xls"}
];
$scope.choices = [];
$scope.addNewChoice = function() {
var newChoiceID = 'choice'+$scope.choices.length+1;
for(var i=0;i<$scope.items.length;i++){
if($scope.items[i].choiceID==null){
$scope.items[i].choiceID = newChoiceID;
$scope.choices.push({'id':newChoiceID,TYPE_ID:$scope.items[i].TYPE_ID});
break;
}
}
};
$scope.updateValue = function(choice) {
for(var i=0;i<$scope.items.length;i++){
if($scope.items[i].choiceID==choice.id)
$scope.items[i].choiceID = null;
if($scope.items[i].TYPE_ID==choice.TYPE_ID)
$scope.items[i].choiceID = choice.id;
}
};
$scope.addNewChoice();
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset ng-repeat="choice in choices">
<select ng-model="choice.TYPE_ID" ng-change="updateValue(choice)">
<option ng-repeat = "item in items | itemFilter:choice" value="{{item.TYPE_ID}}">{{item.TYPE_NAME}}</option>
</select>
</fieldset>
<button class="addfields" ng-show="items.length>choices.length" ng-click="addNewChoice()">Add fields</button>
<h4>Data for backend</h4>
<ul>
<li ng-repeat="choice in choices">TYPE_ID: {{choice.TYPE_ID}}</li>
</ul>
</div>
You can try this solution, which works based on the first options selected value, based on the requirement you can change it.
var app = angular.module('angularjs-starter', []);
app.controller('MainCtrl', function($scope) {
$scope.names = ['Mobile','Office','Home'];
$scope.selectedValue = [];
$scope.choices = [{id: 'choice1', options: $scope.names}];
$scope.addNewChoice = function() {
var newItemNo = $scope.choices.length+1;
// First Frame options list
var ele = document.getElementById('myOptions');
var angularEle = angular.element( ele );
var value = angularEle[0].value;
$scope.selectedValue = $scope.names.filter(item => item !== value)
$scope.choices.push({'id':'choice'+newItemNo, options: $scope.selectedValue});
};
});
.addfields {
-webkit-appearance: button;
cursor: pointer;
color: #fff;
background-color: #337ab7;
border-color: #2e6da4;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<div id='mainC' ng-app="angularjs-starter" ng-controller="MainCtrl">
<fieldset ng-model='y' ng-repeat="choise in choices">
<p> <ul>Id, Options
<li ng-repeat="(k,v) in choise">{{v}}</li>
</ul></p>
<select id='myOptions'>
<option ng-model='x1' ng-repeat = "x in choise.options">{{x}}</option>
</select>
</fieldset>
<button class="addfields" ng-click="addNewChoice()">Add fields</button>
</div>

angularjs filters unique filters

How to enable or disable the radio buttons according to available options in the array
// Code goes here
var app = angular.module('app', ['ui.directives','ui.filters']);
app.controller('ctrl', function($scope, $filter,$http) {
$scope.pageNumber = {};
$http.get('https://cdn.rawgit.com/rainnaren/20355aea389ba6f7bfb801ecb52774d6/raw/4482a3d9f5a0cc3e73720a11e0e2b60c085519c0/data.json').then(function(data){
$scope.data = data.data;
angular.forEach($scope.data.products,function(key,value){
angular.forEach(key.productAttributes,function(k,val){
// console.log(key.productAttributes)
// $scope.brandsGroup = uniqueItems(key.productAttributes, val);
// console.log($scope.brandsGroup)
})
})
});
// var uniqueItems = function (data, key) {
// var result = [];
// for (var i = 0; i < Object.keys(data).length; i++) {
// var value = data[i][key];
// if (result.indexOf(value) === -1) {
// result.push(value);
// }
// }
// return result;
// };
$scope.$watch(function() {
return $scope.pageNumber;
}, function() {
$scope.v = function(event,d) {
var count = Object.keys($scope.pageNumber.productAttributes).length;
console.log(count);
if ($scope.data.variantAttributeses.length === count) {
$scope.x = $filter('filter')($scope.data.products, $scope.pageNumber);
}
};
});
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"> </script>
<link rel="stylesheet" href="style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="ctrl">
{{pageNumber}}
<div ng-repeat="d in data.variantAttributeses | unique:d">
{{d.name}}
<div>
<form ng-repeat="dg in data.products | filter:pageNumber ">
<label><input ng-change="v()" type="checkbox" ng-model="pageNumber.productAttributes[d.name]" ng-true-value="'{{dg.productAttributes[d.name] }}'" ng-false-value="''">{{dg.productAttributes[d.name] }}</label>
</form>
</div>
</div>
<div>
<div ng-repeat="data in x | filter:pageNumber:true">
{{data.brandProductId}}
</div>
</div>
</body>
</html>
here the unique filter is not working what is the solution to do this i tried the angular ui filters but in my case it is not working anyone provide me the custom filter for that.
in this the field name is also dynamic . so how to filter the duplicates from the json
here is my working code
The logic for writing the function that determines what is disabled isn't trivial (I just tried for about 15 minutes) ultimately you can use ng-disabled and set a property on the "option" in the data so that it gets reflected in the view, something like
ng-disabled="d.disabled"
ng-change="checkDisabled()"
in the checkDisabled you'd have to run the logic to determine which options actually get the "disabled" attribute added to them for use by ng-disabled here.
Also to keep the filtered data on scope can use:
<div ng-repeat="data in data.products | filter:pageNumber as filtered">
then you will have a $scope.filtered with the filtered products. The trick is you need to go through all radio options and for each one you need to search all products and see if any product doesn't match the option value. If it matches any value then disabled for that option =false if it matches no values of any or the filtered products then it's disabled=true.

In angular js How to do an edit option?

I am trying to do an edit field in angular js but I don't know how to do that one help me
below is my Crud operation code
var app = angular.module('myApp', [])
app.controller('myCtrl', ['$scope', function($scope) {
$scope.products = ["venu", "balaji", "suresh"];
$scope.addItem = function() {
$scope.errortext = "";
if (!$scope.addMe) {
return;
}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe)
} else {
$scope.errortext = "The item is already in your names list.";
}
}
$scope.removeItem = function(x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}<span ng-click="removeItem($index)">×</span>
</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">ADD</button>
<p>{{errortext}}</p>
<p>Try to add the same name twice, and you will get an error message.</p>
</div>
</div>
I am doing crud operations in angular js. i have done Delete and Add but I dont know how to do Edit operation in angular js
var app = angular.module('myApp', [])
app.controller('myCtrl', ['$scope', function($scope) {
$scope.products = ["venu", "balaji", "suresh"];
$scope.addItem = function() {
$scope.errortext = "";
if (!$scope.addMe) {
return;
}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe)
} else {
$scope.errortext = "The item is already in your names list.";
}
$scope.addMe = "";
}
$scope.removeItem = function(x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
$scope.edit = function(index){
$scope.addMe = $scope.products[index];
$scope.products.splice(index, 1);
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}
<span ng-click="removeItem($index)">×</span>
<span style="color:blue;cursor:pointer;" ng-click="edit($index)">Edit</span>
</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">ADD</button>
<p>{{errortext}}</p>
<p>Try to add the same name twice, and you will get an error message.</p>
</div>
</div>
Try this.
The solution is here:
HTML
<li ng-repeat="x in products" ng-click="preEdit(x, $index)">{{x}}<span ng-click="removeItem($index)">×</span></li>
<input ng-model="addMe">
<button ng-if="isAdd" ng-click="addItem()">ADD</button>
<button ng-if="!isAdd" ng-click="editItem()">EDIT</button>
JS
$scope.isAdd = true;
$scope.preEdit = preEdit;
var index = '';
function preEdit(x, i){
$scope.addMe = x;
index = i;
$scope.isAdd = false;
}
$scope.editItem = editItem ;
function editItem (){
$scope.products[index] = $scope.addMe;
$scope.isAdd = true;
$scope.addMe = '';
index = '';
}
Look my solution in filddle: https://jsfiddle.net/tfx8njw6/
At first you need to add a edit option on the <li> say,
<ul>
<li ng-repeat="x in products">{{x}}
<span ng-click="removeItem($index)">×</span>
<span ng-click="editItem($index)">Edit</span>
</li>
</ul>
Then add a controller function for edit editItem() like
$scope.editItem= function(index) {
$scope.addMe = $scope.products[index];
//this variable will allow you to check whether the operation is an edit or add
$scope.editIndex = index;
}
You can then reuse your addItem() function like this
$scope.addItem = function() {
$scope.errortext = "";
if (!$scope.addMe) {
return;
}
if(angular.isDefined($scope.editIndex)){
$scope.products[$scope.editIndex] = $scope.addMe;
//reset the variable to undefined after using it
$scope.editIndex = undefined;
}else{
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your names list.";
}
}
}
If you want to take it to the "next level", check out xeditable. :)
https://vitalets.github.io/angular-xeditable/#text-simple
Good luck!
For Edit what you can do:
0.Pass the id on edit click and get data of that id and assign to the same variable you have used for add and hide add button and show update button.
1.Either use the same text field which you are using for add and show/hide button add/update accordingly.
2.You can use separately div which includes one text box and button to update.Show/hide as per you action.

How to add a search for example by category?

How to add a search for example by category ?? How is it connected to filteredUsers ?? Help me please... If just add a filter pagination does not work properly. I do so.But I do not know where to add the filter:
var app = angular.module('appTelDirectory', []);
app.controller('directoryList', function($scope, $filter) {
$scope.currentPage = 0;
$scope.pageSize = 10;
$scope.users = [];
$scope.category = [{'name':'cat1'},{'name':'cat2'}]
// Using a separate list of filtered users
$scope.filteredUsers = [{}];
$scope.numberOfPages = function() {
return Math.ceil($scope.filteredUsers.length / $scope.pageSize);
}
for (var i = 0; i < 45; i++) {
if(i % 2 == 0) {
cat = 'cat1'
}
else cat= 'cat2';
$scope.users.push({'name':'user'+i,'category':''+cat});
}
$scope.filteredUsers = angular.copy($scope.users);
$scope.$watch('searchAll', function(newValue) {
// Manually filtering here instead doing in the view
$scope.filteredUsers = $filter('filter')($scope.users, {$: newValue});
});
});
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="appTelDirectory" ng-controller="directoryList">
<input placeholder="Поиск..." ng-model="searchAll" class="form-control">
<span> Категория </span>
<select>
<option ng-repeat="category in category | filter:answer">{{category.name}}</option>
</select>
<ul>
<li ng-repeat="item in filteredUsers | startFrom:currentPage*pageSize | limitTo:pageSize">{{item.name}}---->>{{item.category}}</li>
</ul>
<table>
<tr ng-repeat="item in users | startFrom:currentPage*pageSize | limitTo:pageSize">
</table>
<button ng-disabled="currentPage == 0" ng-click="currentPage=currentPage-1">Previous</button>
{{currentPage+1}}/{{numberOfPages()}}
<button ng-disabled="currentPage >= filteredUsers.length/pageSize - 1" ng-click="currentPage=currentPage+1">
Next
</button>
</div>
I would be grateful for any help.
Add an ng-model to your select.
<select ng-model="selectedCat">
<option ng-repeat="category in category | filter:answer">{{category.name}} </option>
</select>
Add the code to do filter based on category also in the watcher function,
$scope.$watch('searchAll', function(newValue) {
// Manually filtering here instead doing in the view
$scope.filteredUsers = $filter('filter')($scope.users, {$: newValue});
$scope.filteredUsers = $filter('filter')($scope.filteredUsers, {$: $scope.selectedCat});
});
// Another watcher to listen change in the selected category
$scope.$watch('selectedCat', function(newValue) {
// Manually filtering here instead doing in the view
$scope.filteredUsers = $filter('filter')($scope.users, {$: newValue});
$scope.filteredUsers = $filter('filter')($scope.filteredUsers, {$: $scope.searchAll});
});

angular input bind two fields

UPDATE
I thought about this and this is what I'm thinking. Maybe I can just filter the list on input (when I type into the input box) rather than automatically have this filter. Is this possible?
I've created a combo box with angular, and I've bound a scope variable to my input using ng-model. Right now the functionality is, you can search for an item in the dropdown. when you click on an item in the dropdown, that value is copied into the input.
however, when I go back into the input to search again, it only brings up items that match the search, which is expected. But I'd like to make it so when you click on the input again, the text that was in the input stays there, but the drop down shows all results.
is this doable? Maybe I can bind a different scope variable to the value of the input?
heres the fiddle: https://jsfiddle.net/mLsbmfb7/25/
html:
<div class='center' ng-app="myapp" ng-controller="appCont">
<div class='form-box'>
<div class='inputs-box'>
<div>
<span>First</span>
<input type='text' ng-model="firstname"/>
</div>
<div>
<span>Last</span>
<input type='text' ng-model="lastname"/>
</div>
</div>
<div class='add-button' ng-click="addPerson()">
add
</div>
</div>
<div class='ppl-list-title'>
<div class='inputs-box'>
<div class='inline-block-top find-word'>Find</div>
<div class='inline-block-top'>
<input id='filter-input' type='text' ng-model='filterText'/>
<div>
<ul class='hidden'>
<li ng-repeat='person in people2 | filter:{fullName:filterText}'
ng-click='setInputValue(person.fullName)'>
<span class=''>{{person.fullName}}</span>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
controller and jquery:
var myapp = angular.module("myapp", []);
myapp.controller('appCont', function($scope) {
$scope.firstname = "";
$scope.lastname = "";
$scope.fullname = function() {
return $scope.firstname + ' ' + $scope.lastname;
};
var Person = function(){
this.firstname = "";
this.lastname = "";
this.isActive = true;
this.fullName = "";
};
function getFullName(first, last) {
return first
+ " "
+ last
};
function getPerson(first, last, active) {
var newPerson = new Person();
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
newPerson.fullName = first + ' ' + last;
return newPerson;
};
$scope.addPerson = function() {
var personToAdd =
getPerson($scope.firstname, $scope.lastname, true);
$scope.people2.push(personToAdd);
$scope.firstname = '';
$scope.lastname = '';
};
$scope.setInputValue = function(full) {
$scope.filterText = full;
};
$scope.people2 = [
getPerson("first", "test", true),
getPerson("second", "try", false),
getPerson("third", "testing", true)];
});
$(document).ready(function() {
$('#filter-input').on('focusin', function() {
$('ul').slideToggle();
});
$('#filter-input').on('focusout', function() {
$('ul').slideToggle();
});
});
function stringFullTrim(word) {
while(word.indexOf(' ') > -1) {
word = word.replace(' ', ' ');
}
return word.trim();
}
Did it by using a fake text input to update the real filter.
<input id='filter-input' type='text' ng-model='temp' ng-keyup='filterText = temp'/>
<input id='filter-input' type='hidden' ng-model='filterText'/>
Then on selecting, copy text into it and wipe the filter, so next search would be fresh again.
<li ng-repeat='person in people2 | filter:{fullName:filterText}'
ng-click='setInputValue(person.fullName); $parent.temp = person.fullName; $parent.filterText = ""'>
You might want to handle some edge cases like user typed the full thing but didn't select.
Note: the $parent is used because of ng-repeat is creating a child scope. The usual way to solve this is to use "the dot" but sometimes I feel like using $parent.
I've edited your fiddle

Categories

Resources