dynamically dropdowns through angularjs - javascript

Having one select tag in html now i want to make select tag dynamic through angularjs so that i can get drop downs from one select options and also want to give different ng-options for every new drop down created
"<div>
<label>dropdown1</label>
<select ng-options=''></select>
</div>"

To be honest, your question is for me a little unclear, but it may help you:
<div ng-repeat="object in myObjects">
<label>{{object.name}}</label>
<select ng-options="object.myOptions"></select>
</div>
this in js:
function AppCtrl ($scope) {
$scope.myObjects = {
"Select1": {
"name": "dropdown1",
"myOptions": [
"one",
"two"
]
}, ....

var app =angular.module('pof', []);
app.controller('myController2', function($scope){
$scope.statuses = [{
id: 1,
name: "First Value"
}, {
id: 2,
name: "Second Value"
}, {
id: 3,
name: "Third Value"
}, {
id: 4,
name: "Fourth Value"
}];
$scope.selected_status = 3;
})
app.directive('bsDropdown', function ($compile) {
return {
restrict: 'E',
scope: {
items: '=dropdownData',
doSelect: '&selectVal',
selectedItem: '=preselectedItem'
},
link: function (scope, element, attrs) {
var html = '';
switch (attrs.menuType) {
case "button":
html += '<div class="btn-group"><button class="btn button-label btn-info">Action</button><button class="btn btn-info dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>';
break;
default:
html += '<div class="dropdown"><a class="dropdown-toggle" role="button" data-toggle="dropdown" href="javascript:;">Dropdown<b class="caret"></b></a>';
break;
}
html += '<ul class="dropdown-menu"><li ng-repeat="item in items"><a tabindex="-1" data-ng-click="selectVal(item)">{{item.name}}</a></li></ul></div>';
element.append($compile(html)(scope));
for (var i = 0; i < scope.items.length; i++) {
if (scope.items[i].id === scope.selectedItem) {
scope.bSelectedItem = scope.items[i];
break;
}
}
scope.selectVal = function (item) {
switch (attrs.menuType) {
case "button":
$('button.button-label', element).html(item.name);
break;
default:
$('a.dropdown-toggle', element).html('<b class="caret"></b> ' + item.name);
break;
}
scope.doSelect({
selectedVal: item.id
});
};
scope.selectVal(scope.bSelectedItem);
}
};
});
<link href="http://st.pimg.net/cdn/libs/bootstrap/2.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script src = "http://st.pimg.net/cdn/libs/jquery/1.8/jquery.min.js">
</script>
<script src = "http://st.pimg.net/cdn/libs/bootstrap/2/js/bootstrap.min.js">
</script>
<body ng-app="pof">
<div ng-controller="myController2 as myCtrl2">
<select ng-init="selected_status = statuses[1].id" ng-model="selected_status" ng-options="status.id as status.name for status in statuses"></select>
<!--<bs-dropdown data-menu-type="button" select-val="selected_status = selectedVal"
preselected-item="selected_status" data-dropdown-data="statuses"></bs-dropdown> --> Selected Value : {{selected_status}}
</div>
</body>

I don't know what your model looks like but maybe something like this:
<div ng-repeat="item in items">
<label>{{item.label}}</label>
<select ng-options="item.options"></select>
</div>
In your controller you would have an array $scope.items that contain all your dropdowns/select elements and their options.
$scope.items = [
{'label':'Item 1','options':{"option 1.1","option 1.2"}},
{'label':'Item 2','options':{"option 2.1","option 2.2"}}
];

Related

Assign css class using ng-class in angular js

I'm using angularjs and I have data like this :
$scope.users = [{
name: "Pratik"
queue: [{number: "199"},{number: "111"}],
status: "OK"
}]
My view :
.available{
background-color: #00226f;
color: #f8f8f8;
}
<div class="col-xs-12 col-sm-3" ng-repeat="user in users">
<span ng-class="{'available': user.queue[0].number == 111}" class="badges ">111</span>
</div>
My problem is that I want to assign the class "available" if the queue array in users contains the number "111" at any index. In the users array the number:"111" may appear at any index so in the view I can't always use user.queue[1].number == 111 or user.queue[1].number == 111 to assign the class. I want a solution which will check if the queue array contains number:"111" and assign the class of available accordingly.
I tried to do it like this : ng-class="{'available': user.queue[i].number == 111}" but it's not working. How do I do it?
This my current workaround to apply the class:
ng-class="{'available': user.queue[0].number == 111 || user.queue[1].number == 111}"
try below code snippet
can achieve by using lodash js also using _.filter
_.filter(array, { 'number': '111' } )
Ref: https://lodash.com/docs/4.17.11#find
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.findObjectByKey = function(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
};
$scope.users = [{
name: "Pratik",
queue: [{number: "199"},{number: "666"}],
status: "OK"
},
{
name: "Pratik 2",
queue: [{number: "111"},{number: "555"}],
status: "OK 2"
},
{
name: "Pratik 3",
queue: [{number: "999"},{number: "888"}],
status: "OK 3"
}
];
$scope.searcInArray = function(array){
// var obj = $scope.findObjectByKey(array, 'number', '111');
// using loadsh
var obj = _.filter(array, { 'number': '111' } );
return obj.length > 0;
};
}
.available{
background-color: #00226f;
color: #f8f8f8;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="MyCtrl">
<div class="col-xs-12 col-sm-3" ng-repeat="user in users">
<span ng-class="{'available' : searcInArray(user.queue)}" class="badges ">111</span>
</div>
</div>
</body>
</html>
You have to add use ng-repeat to loop all queue and find how has item.number == '111'
<div class="col-xs-12 col-sm-3" ng-repeat="user in users">
<div ng-repeat="item in user.queue">
<span ng-class="{'available': item.number == '111'}" class="badges ">111</span>
</div>
</div>
NOTE!
if you want show only the item.number == '111' you can use ng-hide/show
To check that condition where 111 appears at any index the easy fix could be to call a function that will check that property in the array and return true or false based on the condition. Something like below:
var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', function($scope){
$scope.users = [{
name: "Pratik",
queue: [{
number: "111"
}, {
number: "119"
}],
status: "OK"
},
{
name: "Pratik123",
queue: [{
number: "199"
}, {
number: "185"
}],
status: "OK"
}];
$scope.checkQueue = function(queue){
return queue.find(({number})=>number === '111');
}
}]);
.available {
background-color: #00226f;
color: #f8f8f8;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">
<div class="col-xs-12 col-sm-3" ng-repeat="user in users">
<span ng-class="{'available': checkQueue(user.queue)}" class="badges ">{{user.name}}</span>
</div>
</div>

Replace $scope with this by turning on ControllerAs

I thought to replace $scope with this keyword in my sample Angular code base and in turn to switch to using ControllerAs syntax.
But in turn this does not seem to work now.
I have a list of countries in my controller and in my custom directive whenever a country name is clicked , I show the map of the respective country.
<body ng-controller="appCtrl as vm">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Welcome to the world of directives!</a>
</div>
<ul class="nav navbar-nav">
<li ng-repeat="countryTab in vm.countries" ng-click="vm.itemClicked(countryTab)" style="cursor:pointer">
<a>{{countryTab.label}}</a>
</li>
<br>
</ul>
</div>
</nav>
<data-country-tab-bar country="vm.selectedCountry" ng-if="vm.selectedCountry">
<strong><i>Check out our cool new directive!</i></strong>
</data-country-tab-bar>
<script>
var app = angular.module('app',[]);
app.controller('appCtrl',function($scope,$http){
this.countries = [{
id: 1,
label: 'Italy',
coords: '41.29246,12.5736108'
}, {
id: 2,
label: 'Japan',
coords: '37.4900318,136.4664008'
}, {
id: 3,
label: 'USA',
coords: '37.6,-95.665'
}, {
id: 4,
label: 'India',
coords: '20.5937,78.9629'
}];
this.itemClicked = function(value){
this.selectedCountry = value;
}
});
And in my directive , I just bind the country object that is the part of my DDO's isolated scope , to that of the controller's.
app.directive('countryTabBar',function(){
return {
restrict: 'E',
transclude:true,
replace:true,
$scope:{
country: '='
},
template: '<div>'+
' <div><strong>{{country.label }}</strong> : {{ country.coords}}</div>'+
' <br/>'+
' <img ng-src="https://maps.googleapis.com/maps/api/staticmap?center={{country.coords}}&zoom=4&size=800x200"> '+
' <br/><br/>'+
' <div ng-transclude></div>'+
'</div>',
}
});
</script>
</body>
But , I can see the transcluded string Check out our cool new directive! but I can't see the map.
There is no error as such in console.
Please help.
I think the problem is related to:
this.itemClicked = function(value){
this.selectedCountry = value;
}
this.selectedCountry in a function declared so in JavaScript will refer to the current function, not the controller (parent function) as you expect.
Solution (ES5):
var vm = this;
this.itemClicked = function(value){
vm.selectedCountry = value;
}
Solution (ES6):
this.itemClicked = value => this.selectedCountry = value;
Additionally, the directive scope syntax seems to be incorrect:
$scope:{
country: '='
},
Should be:
scope:{
country: '='
},
Hope this helps.

how to count the checkbox which was checked using angular?

Here, I used $watch to display the counter value.
But the counter value not increased yet,
To Count,
$scope.$watch('items', function(items){
var selectedItems = 0;
angular.forEach(items, function(item){
selectedItems += item.selected ? 1 : 0;
})
$scope.selectedItems = selectedItems;
}, true);
In UI,
<div class="col-sm-4" ng-repeat="item in items">
<label class="chkbox-holder cbox mbot10" for="List-{{$index}}"><input ng-model="item.Selected" type="checkbox" id="List-{{$index}}"><label for="List-{{$index}}"></label>{{item.name}}</label>
</div>
To display the counter value,
<div>Selected Items Length: {{selectedItems}}</div>
But still the counter is 0;
JSON Value from http service is,
[
{
"id": 1,
"refCode": "",
"name": "pragadees"
},
{
"id": 2,
"refCode": "",
"name": "pragadees"
}......]
Can anyone please help on this.
You've just got a typo error. Your markup is bound to item.Selected while your JavaScript is checking for item.selected. Renaming them properly solves your problem. I'd recommend using lower key inside ot html.
<input ng-model="item.selected" type="checkbox" id="List-{{$index}}">
^-- See here
Demo
first of all, you got a typo in your ng-model, it is item.selected not item.Selected that's maybe why it does not match nothing...
And this is how i'll write it, using basic angular two way data binding, no extra counters, watches, triggers, ....
angular.module('myApp', []);
angular.module('myApp').controller('Ctrl', ['$scope', function($scope) {
$scope.items = [{
name: "Doe"
}, {
name: "Adam"
}, {
name: "Ado"
}, {
name: "Brown"
}, {
name: "Heather"
}, {
name: "Stan"
}];
$scope.itemsSelected = function() {
return $scope.items.filter(function(i) {
return i.selected
}).length;
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="Ctrl">
<h2>current active selected options {{ itemsSelected() }}</h2>
<ul>
<div ng-repeat="item in items">
<label for="List-{{$index}}">
<input ng-model="item.selected" type="checkbox" id="List-{{$index}}">
<label for="List-{{$index}}"></label>{{item.name}}</label>
</div>
</ul>
</body>
You can use ng-change instead:
var app = angular.module("app", []);
app.controller("myCtrl", function($scope) {
$scope.items = [
{name: 'A', value: 'a'},
{name: 'B', value: 'b'},
{name: 'C', value: 'c'},
{name: 'D', value: 'd'},
{name: 'E', value: 'e'}
];
$scope.counter = 0;
$scope.change = function(e) {
if(e){
$scope.counter +=1;
}else{
if($scope.counter > 0) $scope.counter -=1;
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<div class="col-sm-4" ng-repeat="item in items">
<label class="chkbox-holder cbox mbot10" for="List-{{$index}}">
<input ng-model="item.Selected" type="checkbox" id="List-{{$index}}"
ng-change="change(item.Selected)">
<label for="List-{{$index}}"></label>{{item.name}}</label>
</div>
Counter: {{counter}}
</div>

Get ngrepeat $index with getElementById()

I am new to AngularJs and I am curious on what is the best approach to getting then index of an ngrepeat on an input and comparing to see if the new string is different from the original value:
js:
var checkIfDataSampleHasChanged = document.getElementById('dsField' + i).value;
console.log(checkIfDataSampleHasChanged);
console.log($scope.currentSchema)
if (checkIfDataSampleHasChanged != $scope.currentSchema.sDataSamples.dsName) {
console.log("hello there")
$scope.currentSchema.sDataSamples.dsName = checkIfDataSampleHasChanged;
}
html:
<fieldset ng-repeat="ds in currentSchema.sDataSamples track by $index">
<label for="{{dsField$index}}" style="width:400px;">
Data Sample Name ({{ds.dsFileName}}):</label>
<input name="{{dsField$index}}" type="text" style="width: 400px;" ng-model="currentSchema.sDataSamples[$index].dsName" value="{{ds.dsName}}" />
<br>
<br>
</fieldset>
You can use a data to hold the initial value and then compare the changed value. You can do this in pure angularjs constructs without using document.getElementById and other hacks:
angular
.module('app', [])
.controller('AppController', function ($scope) {
var initialSample = [
{id: 1, name: 'Abc'},
{id: 2, name: 'def'},
{id: 3, name: 'ghi'},
{id: 4, name: 'jkl'},
{id: 5, name: 'mno'}
];
$scope.sample = angular.merge([], initialSample);
$scope.checkIfValueChanged = function ($index) {
var isValChanged = initialSample[$index].name !== $scope.sample[$index].name;
console.log(isValChanged);
if (isValChanged) {
alert("Value has changed");
} else {
alert("Value has not changed");
}
};
$scope.changeVal = function(){
var randInt = Math.floor(Math.random() * 5);
console.log(randInt);
$scope.sample[randInt].name = "Lorem ipsum";
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<div ng-app='app' ng-controller='AppController'>
<ul>
<li ng-repeat="item in sample" ng-click="checkIfValueChanged($index)">
{{item.name}}
</li>
</ul>
<button ng-click="changeVal()"> Change random value </button>
</div>

On ng-checked i need data inside div to be displayed

I have a table with 'n' number of rows and each row has a checkbox. Upon selection of checkbox I am trying to display information coded inside <div> tag.
But even if check box has false value the data inside div is still displayed, am using ng-show in div tag to check if checkbox is true or false.
Below is the code I have used in table column:
<td>
<input id="{{test}}" type="checkbox" value="" ng-checked="selection.indexOf(test) > -1" ng-click="toggleSelection(test)" />
</td>
In JavaScript I have the below toggle function
toggle selection for a given line item by index
$scope.toggleSelection = function toggleSelection(test) {
var idx = $scope.selection.indexOf(test);
if it is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
if it is newly selected
else {
$scope.selection.push(test);
}
};
Please point me if I am doing in wrong way, am pretty new to angular world.
this example might be pretty good for your case
<a href="http://jsfiddle.net/t7kr8/211/" >Click here </a>
Make sure you are binding model with ng-show
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
var _this = this;
$scope.tempArr = [{
status: false,
data: 'hey'
}, {
status: false,
data: 'hey'
}, {
status: false,
data: 'hey'
}];
$scope.tempArr = [{
status: false,
data: 'hey'
}, {
status: false,
data: 'hey'
}, {
status: false,
data: 'hey'
}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="myApp" ng-controller="formCtrl">
<table>
<tr ng-repeat="item in tempArr">
<td>
<input type="checkbox" ng-model="item.status">
</td>
<td><span ng-show="item.status">{{item.data}}</span>
</td>
</tr>
</table>
</div>
<div ng-app="checkbox" ng-controller="homeCtrl">
<div ng-repeat="item in list">
<input type="checkbox" checkbox-group />
<label>{{item.value}}</label>
</div>{{array}}
<br>{{update()}}
</div>
var app = angular.module('checkbox', []);
app.controller('homeCtrl', function($scope) {
$scope.array = [1, 5];
$scope.array_ = angular.copy($scope.array);
$scope.list = [{
"id": 1,
"value": "apple",
}, {
"id": 3,
"value": "orange",
}, {
"id": 5,
"value": "pear"
}];
$scope.update = function() {
if ($scope.array.toString() !== $scope.array_.toString()) {
return "Changed";
} else {
return "Not Changed";
}
};
})
.directive("checkboxGroup", function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
// Determine initial checked boxes
if (scope.array.indexOf(scope.item.id) !== -1) {
elem[0].checked = true;
}
// Update array on click
elem.bind('click', function() {
var index = scope.array.indexOf(scope.item.id);
// Add if checked
if (elem[0].checked) {
if (index === -1) scope.array.push(scope.item.id);
}
// Remove if unchecked
else {
if (index !== -1) scope.array.splice(index, 1);
}
// Sort and update DOM display
scope.$apply(scope.array.sort(function(a, b) {
return a - b
}));
});
}
}
});

Categories