I have a angularjs function which contain an array of values as follows
$scope.arrayVal = function()
{
var array = [{id:1,name:"one"},{id:2,name:"two"}];
}
I am passing this array to my dropdown which is in the html page and show the values in a dropdown as follows
<html>
<select ng-model="data.selected">
<option value="item.id,item.name" ng-repeat="item in array">{{item.id}} {{item.name}}</option>
</html>
What I want to achieve is I want to make user select multiple values from the dropdown and these selected values should be displayed according to the selected order below the dropdown. How can I achieve this with angularjs and html only. (I am not using any libraries other than angularjs)
Try this plunker https://next.plnkr.co/edit/6Nxaxz9hGNXospyT. You might have to tinker with it to get the outcome you want
<div ng-controller="ctrl">
<select ng-model="selectedItem" ng-options="item.name for item in items" ng-change="selectItem()">
</select>
<p ng-repeat="item in selectedItems">{{item.id}} - {{item.name}}</p>
</div>
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.items = [{id:1,name:"one"},{id:2,name:"two"}];
$scope.selectedItems = [];
$scope.selectedItem;
$scope.selectItem = function () {
var index = $scope.selectedItems.findIndex(function (fItem) { return $scope.selectedItem.id === fItem.id; });
console.log(index)
if (index > -1) $scope.selectedItems.splice(index, 1);
else $scope.selectedItems.push($scope.selectedItem);
};
});
Related
I am using angularjs here my div will come based on onchange of drop down.Here I need to limit the h4 tag to only once based on its value.if suppose my value is critical coming multiple times it should be only once again if my value is major coming multiple times it should be only once like that.these values are coming from json so it is dynamic.Can anyone please help am new to angularjs,here is the code below
html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="condition">condition</option>
</select>
<div class="main">
<div ng-repeat="emp in groups" ng-attr-id="{{emp[attr]}}">
<h4 id="test" class="{{emp[attr]}}">{{emp[attr]}}</h4>
</div>
</div>
</div>
script
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [
{
name: 'Malaria',
symptom:'fever',
categoty:'critical',
id:'1'
},
{
name: 'cancer',
symptom:'diesease',
categoty:'critical',
id:'3'
},
{
name: 'fever',
symptom:'diesease',
categoty:'major',
id:'3'
},
{
name: 'Cold',
symptom:'colds',
categoty:'major',
id:'2'
}
]
$scope.update = function() {
if($scope.x == 'condition'){
$scope.id='categoty';
$scope.attr = 'categoty';
}
}
});
You were a bit ambiguous when you say "is coming only once in the data". I think the behavior you are looking for in the shared plnkr is to allow the user to select an attribute and group by that attribute showing only the name property listed under the individual groupings.
To accomplish this, I built a selection of attributes the user can pick. So if a minor property is added to the objects in the future, it will continue to function and that can be added to the picker.
After picking an item, the data is parsed and it groups the items by the selected attribute. Each group is a key (selected attribute) mapping to an array (the item names). Once the grouping is made, two ng-repeats can display their data. The top level ng-repeat for each group category and the nested ng-repeat to show the items/names under the group.
var jsonData = [
{
name: 'Malaria',
symptom:'Fever',
category:'Critical',
id:'1'
},
{
name: 'Cancer',
symptom:'Diesease',
category:'Critical',
id:'3'
},
{
name: 'Fever',
symptom:'Diesease',
category:'Major',
id:'3'
},
{
name: 'Cold',
symptom:'Colds',
category:'Major',
id:'2'
}
];
// Setup angular
angular.module('myApp', [])
.controller('MainController', function MainController() {
var self = this;
// Setup your dropdown selections to choose an attribute
self.attrs = [
'category',
'symptom'
];
// On selection change, update how groups is built
self.onSelect = function onSelect(attr) {
// First build a map of all items grouped by attr
var groupMap = {};
jsonData.forEach(function group(item) {
var attrVal = item[attr],
arr = groupMap[attrVal];
if (!arr) {
arr = groupMap[attrVal] = [];
}
// Push the item name
arr.push(item.name);
});
self.groups = groupMap;
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.10/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainController as $ctrl">
Select Attribute:
<select ng-model="$ctrl.selectedAttr" ng-change="$ctrl.onSelect($ctrl.selectedAttr)">
<option ng-repeat="attr in $ctrl.attrs">{{::attr}}</option>
</select>
<div ng-show="::$ctrl.selectedAttr">
<div ng-repeat="(attr, names) in $ctrl.groups">
<h4>{{::attr}}</h4>
<ul>
<li ng-repeat="name in names">{{::name}}</li>
</ul>
</div>
</div>
</div>
Problem description:
I want to create an add-on on my google sheet (g-1). When the user opens the add-on, I want to immediately read another google spreadsheet (g-2) and populate dropdowns on g-1 based on those columns.
I have enabled the Googlesheet Api
in Code.js:
function readSpreadsheet() {
var questions = Sheets.Spreadsheets.Values.get("_ID_", "SHEET!A2:k").values
if (!questions) {
return 'No data found.';
} else {
return questions
}
}
the function above works, because if I add that to the title on the add-on I see the correct number of columns:
HtmlService.createHtmlOutputFromFile('QuestionBank').setTitle(readSpreadsheet().length)
or I can print the first row
readSpreadsheet()[0]
............
So far so good.
Now in my html file, QuestionBank.html,
Problem #1. I am not able to call readSpreadsheet, it returns undefined. var question_rows returns undefined.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
/**
read all rows, upon clicking on sync button. But this is not necessary if I can populate the dropdowns on load
**/
$(function() {
$('#sync').click(readSpreadsheet);
});
function readSpreadsheet() {
this.disabled = true;
$('#error').remove();
var question_rows = google.script.run
.withSuccessHandler(
function(textAndTranslation, element) {
element.disabled = false;
})
.withFailureHandler(
function(msg, element) {
element.disabled = false;
})
.withUserObject(this)
.readSpreadsheet();
for (var row = 0; row < question_rows.length; row++) {
alert(question_rows[row])
}
}
</script>
Problem #2: I have several dropdowns that I want their value to be unique value of the g-2 columns. I want those dropdowns to be populated when the add-on opens.
<select class="filter">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
so instead of Volvo, etc, I want the first column of my data, unique values
Problem #3: if on load is not possible, I can include a button to read the data and populate the dropdowns
<button class="sync-button" id="sync">sync</button>
How about the following answers?
Answer for Problem #1
google.script.run doesn't return values. When it uses values from google.script.run, in your case, textAndTranslation of withSuccessHandler is the returned value. So you can modify readSpreadsheet() as follows.
function readSpreadsheet() {
this.disabled = true;
$('#error').remove();
google.script.run
.withSuccessHandler(withSuccessHandler)
.withFailureHandler(
function(msg, element) {
element.disabled = false;
})
.withUserObject(this)
.readSpreadsheet();
}
function withSuccessHandler(textAndTranslation, element) {
element.disabled = false;
var question_rows = textAndTranslation;
for (var row = 0; row < question_rows.length; row++) {
alert(question_rows[row])
}
}
Answer for Problem #2
You can achieve it by putting google.script.run in $(function() {}). The sample is as follows. This is a sample. So please modify the variables to yours.
<select class="filter"></select>
<script>
$(function() {
google.script.run.withSuccessHandler(sample).readSpreadsheet();
});
function sample(data) {
for (var i=0; i < data.length; i++) {
$('.filter').append($('<option>').html(data[i]).val(data[i]));
}
}
Answer for Problem #3
Of course, you can set values to <select class="filter"></select> using a button.
If I misunderstand your questions, I'm sorry.
I'm currently working on a project where I have a button that adds a dropdown everytime you click on the button.
Clicking the button not only shows the dropdown, but also a "Remove item" button, where you can remove the respective item added.
Then if you select an option from the dropdown, it will show another dropdown with more options, depending on what you chose on the first dropdown.
You can choose from the dropdown two options, movies or games.
And then on the second dropdown should appear a movie list or a game list depending on what you selected.
You can see HERE the current fiddle.
index.html:
<div ng-app="myApp" ng-controller="testCtrl">
<button ng-click = "addNewItem()">Add new Item</button>
<div ng-repeat="item in itemSet.item track by $index">
<button ng-click = "removeItem($index)">Remove item</button>
<select ng-model="category"
ng-change="changeCategory(category)"
ng-options="category as category for category in categoryTypes">
<option></option>
</select>
<select ng-show="movieSelected"
ng-model="movieType"
ng-options="movie as movie for movie in movieCategories">
<option></option>
</select>
<select ng-show="gameSelected"
ng-model="gameType"
ng-options="game as game for game in gameCategories">
<option></option>
</select>
</div>
</div>
app.js:
var myApp = angular.module('myApp', []);
myApp.controller('testCtrl', ['$scope', function ($scope) {
$scope.categoryTypes = ['Movies', 'Games'];
$scope.gameCategories = ['RPG', 'Sports'];
$scope.movieCategories = ['Action', 'SciFi'];
$scope.itemSet = { item : [] };
$scope.itemSet.item = [];
$scope.gameSelected = false;
$scope.movieSelected = false;
$scope.addNewItem = function () {
$scope.itemSet.item.push('');
};
$scope.removeItem = function (index) {
$scope.itemSet.item.splice(index, 1);
};
$scope.changeCategory = function(category) {
if(category == 'Movies') {
$scope.gameSelected = false;
$scope.movieSelected = true;
} else {
$scope.gameSelected = true;
$scope.movieSelected = false;
}
};
}]);
There are some things that are going wrong with this. With no order in particular:
For example, if I added 3 items, and then want to delete the first one, it will delete the third, then the second and finally the first if you keep pressing the "Remove Item" button.
If I add 3 items and I select "movies" from the first dropdown on the first row for example, it will display all of the other dropdowns with the possibility of choosing the items from the movie list on all of them, even if I didn't choose anything from the other rows.
Also if you want to add, lets say, 2 items, in one item you pick first "movies" and then on the second one you pick "games", the "extra" dropdowns will show the list of games instead of the respective list of items for each of the cases.
The actual project works similar to this, but with 4 dropdowns, and the information comes from a database but I guess that with the Fiddle should be enough to get the idea and to take a possible solution to the actual project.
If someone could help me out on this one I'll be very gratefull!
Your code has a big problem that is: you have the same ngModel for all items in ngRepeat.
After fixing this, you can simplify a lot your code.
You don't need to use ngChange to know what category is selected, you can simply use ngSwitch directive what fits well in this case.
See it working:
(function() {
'use strict';
angular
.module('myApp', [])
.controller('testCtrl', testCtrl);
testCtrl.$inject = ['$scope'];
function testCtrl($scope) {
$scope.categoryTypes = ['Movies', 'Games'];
$scope.gameCategories = ['RPG', 'Sports'];
$scope.movieCategories = ['Action', 'SciFi'];
$scope.itemSet = {
item: []
};
$scope.addNewItem = function() {
$scope.itemSet.item.push({});
};
$scope.removeItem = function(index) {
$scope.itemSet.item.splice(index, 1);
};
}
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="testCtrl">
<button ng-click="addNewItem()">Add new Item</button>
<div ng-repeat="item in itemSet.item track by $index">
<button ng-click="removeItem($index)">Remove item</button>
<select ng-model="item.category"
ng-options="category for category in categoryTypes">
<option value hidden>Select a category</option>
</select>
<span ng-switch="item.category">
<select ng-switch-when="Movies"
ng-model="item.movie"
ng-options="movie for movie in movieCategories">
<option value hidden>Select a movie</option>
</select>
<select ng-switch-when="Games"
ng-model="item.game"
ng-options="game for game in gameCategories">
<option value hidden>Select a game</option>
</select>
</span>
</div>
<pre ng-bind="itemSet.item | json"></pre>
</div>
</body>
</html>
The main problem is you're controls are bound $scope values instead of the individual items you are trying to manipulate. A secondary problem is that you initialize each new array element as an empty string '' instead of an object {}.
This will work:
index.html
<div ng-app="myApp" ng-controller="testCtrl">
<button ng-click = "addNewItem()">Add new Item</button>
<div ng-repeat="item in itemSet.item track by $index">
<button ng-click = "removeItem($index)">Remove item</button>
<select ng-model="item.category"
ng-change="changeCategory(item)"
ng-options="category as category for category in categoryTypes">
<option></option>
</select>
<select ng-show="item.movieSelected"
ng-model="movieType"
ng-options="movie as movie for movie in movieCategories">
<option></option>
</select>
<select ng-show="item.gameSelected"
ng-model="gameType"
ng-options="game as game for game in gameCategories">
<option></option>
</select>
</div>
</div>
app.js
var myApp = angular.module('myApp', []);
myApp.controller('testCtrl', ['$scope', function ($scope) {
$scope.categoryTypes = ['Movies', 'Games'];
$scope.gameCategories = ['RPG', 'Sports'];
$scope.movieCategories = ['Action', 'SciFi'];
$scope.itemSet = { item : [] };
$scope.itemSet.item = [];
$scope.gameSelected = false;
$scope.movieSelected = false;
$scope.addNewItem = function () {
$scope.itemSet.item.push({});
};
$scope.removeItem = function (index) {
$scope.itemSet.item.splice(index, 1);
};
$scope.changeCategory = function(item) {
if(item.category == 'Movies') {
item.gameSelected = false;
item.movieSelected = true;
} else {
item.gameSelected = true;
item.movieSelected = false;
}
};
}]);
Updated fiddle:https://jsfiddle.net/5zwsdbr0/
I want to select all values from a drop down of HTML on ng-click. Here is my HTML code
<select multiple ng-model="selectedToPostalCodes"
ng-options="items.postalcode for items in toPostalCodes">
<option style="display:none;"></option>
</select>
<input type="button" value="Select All" ng-click="selectall()">
So I want the implementation of selectall() function.
Thanks
you can try this way:: Fiddle
fiddleApp.controller('Main', ['$scope', function($scope) {
$scope.toPostalCodes = [
{postalcode:1, name:"Japan"},
{postalcode:4, name:"USA"}
];
$scope.selectedToPostalCodes = [];
$scope.selectall = function(){
$scope.selectedToPostalCodes = [];
angular.forEach($scope.toPostalCodes, function(item){
$scope.selectedToPostalCodes.push( item.postalcode);
});
}
}]);
You can try like this:
$scope.selectall = function() {
var allOptions = [];
// First get all codes as list
angular.forEach($scope.toPostalCodes, function(item) {
allOptions.push(item.postalcode);
});
// And then assign the values to the scope model
$scope.selectedToPostalCodes = allOptions;
};
I have a select box like this...
<select class="form-control m-b"
ng-options="portfolios.id as portfolios.product_name for portfolios in portfolio"
data-ng-model="portfolio" ng-change="getPriceAttributes()">
</select>
When a user selects an option from the select box, the function getPriceAttributes() is called...
(function() {
var app = angular.module('QuoteApp');
var quoteBuilderController = function($scope, $http) {
$scope.formData = {};
// this populates the select
$http.get('scripts/json/sample-products.json')
.then(function(res){
$scope.portfolio = res.data.Connectivity;
});
//this is called when a user selects an option from the select control
$scope.getPriceAttributes = function() {
$http.get('scripts/json/sample-product-attribute-response.json')
.then(function(res){
$scope.formFields = res.data;
});
};
};
app.controller('quoteBuilderController', ['$scope', '$http', quoteBuilderController]);
}());
When I load the page, the select box has a list of options which come from a json file. When I select an option from the select box, getPriceattributes() is called, but the options in the select box disappear, leaving an empty select control. Does anyone know why this might be happening?
Thank you