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>
Related
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);
};
});
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 am working on a simple react example that will alter the content of a header on the screen based on what a user enters in a text field. Here's the react code:
var GreeterForm = React.createClass({
onFormSubmit: function(e){
e.preventDefault();
var name = this.refs.name;
this.refs.name.value = '';
this.props.onNewName(name);
},
render: function(){
return(
<form onSubmit={this.onFormSubmit}>
<input type="text" ref="name"/>
<button>Set Name</button>
</form>
);
}
});
var Greeter = React.createClass({
//returns an object of the default properties to be used
//these are used if no properties are passed in
getDefaultProps: function(){
return {
name: 'React!',
message: "this is from a component!"
};
},
//maintains a state for the component. Maintains the state as an object
//this is a default method for react and we override it.
getInitialState: function(){
return {
name: this.props.name
};
},
handleNewName: function(name){
this.setState({
name: name
});
},
//renders the greeter react component
render: function() {
var name = this.state.name;
var message = this.props.message;
return (
<div>
<h1>Hello {name}!</h1>
<p>{message}</p>
<GreeterForm onNewName={this.handleNewName}/>
</div>
);
}
});
var firstName = "DefaultName";
var mess = "This is a message from react."
//note that name and message are passed in as properties
ReactDOM.render(<Greeter name={firstName} message={mess}/>, document.getElementById('app'));
You can see that GreeterForm is nested within Greeter and is supposed to alter the content of the h1 tag when the user submits.
However, the content of the h1 tag is not changing. I sprinkled alert(name.value) along the code to ensure the correct name from the input field was being passed around, and that all checked out.
What could it be? Is something wrong with my setState function?
Here's the HTML if needed:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
</head>
<body>
<div id="app">
</div>
<script type="text/babel" src="app.jsx"></script>
</body>
</html>
You are not sending value of input. you are sending whole html element
in onFormSubmit function change this line
var name = this.refs.name;
to
var name = this.refs.name.value;
Here's my fiddle: http://jsfiddle.net/VSph2/280/
I'm trying to uncheck a checkbox and reset the values of a scope variable with a link, however, it doesn't seem to work. Could someone help?
Javascript:
var app = angular.module('myApp', []);
app.controller('IndexCtrl', ['$scope', function($scope) {
$scope.colors = [
{id: 1, name: "Blue"},
{id: 2, name: "Green"},
{id: 3, name: "Red"}
];
$scope.color_ids = [];
$scope.clearAll = function() {
angular.forEach($scope.color_ids, function(color_id) {
color_id.checked = false; //nothing works!!
color_id.selected = false; //
});
$scope.color_ids = [];
$scope.color_ids.selected = false; //doesn't work either
};
}]);
HTML:
<div ng-controller="IndexCtrl">{{1+1}}
<h2>Products</h2>
<div class="filters col-two">
<a ng-click="clearAll()">Clear all filters</a>
<h3>Color</h3>
<div ng-repeat="color in colors">
{{ color.name }} <input type="checkbox" ng-model="color_ids">
</div>
</div>
</div>
You never add anything to the color_id array, so the foreach is not iterating over anything.
I updated your code to just use the main color array and add a selected property on it:
http://jsfiddle.net/VSph2/283/
html:
{{ color.name }} <input type="checkbox" ng-model="color.selected">
javascript:
angular.forEach($scope.colors, function(color_id) {
color_id.selected = false;
});
I came across this while looking for something similar, my solution is to reset the color_ids object
$scope.clearAll = function() {
$scope.color_ids = [];
};
You also need to make the following changes to the input
<input type="checkbox" ng-model="color_ids[color.id]" ng-checked="color_ids[color.id]">
jsfiddle at
https://jsfiddle.net/novelnova/VSph2/756/
You are misunderstanding what ng-model on a checkbox does. It will only toggle a specific value set. So in your example, you would want to change it to:
{{ color.name }} <input type="checkbox" ng-model="color.selected">
And then your colors will have an additional attribute called selected that is either true or false, depending on if the box is checked or not.
To clear, you would then loop over all colors and set their selected state to false.
$scope.clearAll = function() {
angular.forEach($scope.colors, function(color) {
color.selected = false;
});
Updated fiddle: http://jsfiddle.net/VSph2/285/
This this question here
KnockoutJS - Databind to a dictionary collection
I'm creating a drop down select from JSON coming from the server.
However at some point after creating it I wish to update the data.
I've created a fiddle
http://jsfiddle.net/LPrf3/
Which shows where I'm at at present. I successfully update the select's observable array.
However... for some reason you need to click into the select from the drop down in order for it to refresh
Javascript:
$(function() {
var destinationsFromServer = {"Europe":"Europe incl Egypt, Turkey & Tunisia","ANZO":"Australia & New Zealand","WorldwideUSA":"Worldwide (incl USA & Canada)"};
var updatedDestinationsFromServer = {"Arctic":"Includes Polar bears and seals","Antarctic":"Just Penguins"};
function mapDictionaryToArray(dictionary) {
var result = [];
for (var key in dictionary) {
if (dictionary.hasOwnProperty(key)) {
result.push({ key: key, value: dictionary[key] });
}
}
return result;
}
function viewModel () {
destinations= ko.observableArray(mapDictionaryToArray(destinationsFromServer));
selectedDestination= ko.observable();
updateDestinations = function()
{
destinations= ko.observableArray(mapDictionaryToArray(updatedDestinationsFromServer));
};
};
ko.applyBindings(new viewModel());
});
HTML
<select data-bind="options: destinations, optionsText: 'key', optionsValue: 'value', value: selectedDestination"></select>
<hr />
<div data-bind="text: selectedDestination"></div>
<button data-bind="click:updateDestinations">UPDATE</button>
How can I get the select to update?
You are reassinging destinations to a new observabelArray instead of updating the array. See this fiddle. When updating any observable, always pass the new value in as a parameter, never assign a new value with the = operatior.
Wrong Way:
updateDestinations = function(){
destinations=ko.observableArray(mapDictionaryToArray(updatedDestinationsFromServer));
};
Right Way:
updateDestinations = function(){
destinations(mapDictionaryToArray(updatedDestinationsFromServer));
};