Parse scope variable name to scope function? - angularjs

I have a dropdown menu and the clickable element that toggles the dropdown. When the user clicks on a list item in the dropdown menu I want to add that value to the input boxes value.
The dropdown menu I have is iterated a defined number of times to create a dropmenu listing incremented numbers.
<!--input-->
<input type="text" value="{{rooms}}">
<!--dropdown-->
<ul role="menu">
<li data-ng-repeat="i in getNumber(num_of_rooms)">
{{$index+1}}
</li>
</ul>
//This function simply returns an array so the dropdown menu repeats a defined number of times
$scope.getNumber = function(n) {
return new Array(n);
};
//I want this scope function to add the value to the input by updating a scope variable
$scope.addToDropDown = function(scope_name, value){
$scope.scope_name = value;
};
-----------
//This works but I'm defining a scope name which I would like to add dynamically as I have multiple dropdown menus
$scope.addToDropDown = function(value){
var val = value+1;
$scope.rooms = val;
};
Is there a way to assign a new value to the scope variable inside the view itself?

Is this what you want? http://plnkr.co/edit/Pew3KIoTy2fVp0tV3xv6?p=preview
give a string of the variable name to the click handler:
<a href="" ng-click="addToDropDown('rooms', $index)">
{{ $index + 1 }}
</a>
just refer the property of the given name in the handler:
$scope.addToDropDown = function(scope_name, value) {
$scope[ scope_name ] = value;
};

Related

How to set a default value for AngularJS ng-repeat?

<li ng-repeat="item in quantityList track by $index" ng-model="isPageValid='true'">
<input value="item.quantity" ng-blur="validateQuantity(item)" ng-model="item.quantity">
</li>
I'm trying to set a default value for a status variable each time an ng-repeat loop occurs. I've tried ng-model, but that doesn't work. For instance,
I'd like to set isPageValid="true" before each time the ng-repeat loop runs. 'True' is will be the default value, and the validation function will test whether isPageValid should be set to 'false'.
I'd like the ng-repeat loop to run each time the ng-blur is exercised.
NOTE: I understand the way I'm using ng-model is incorrect, but this is just to illustrate the issue.
HTML:
<li ng-repeat="item in quantityList track by $index" ng-model="isPageValid='true'">
<input value="item.quantity" ng-blur="validateQuantity(item)" ng-model="item.quantity">
</li>
JS:
scope.validateQuantity = function(item){
var qty = item.quantity;
if(parseInt(qty) >=1 && parseInt(qty) <= 200){
item.isQuantityValid = true;
}else{
item.isQuantityValid = false;
scope.isPageValid = false;
}
}
The loop creates a list of input boxes. The objective is to create a global validation value called isPageValid which is 'false' if the validation by the JS fails for any input box. Note, when ng-blur is exercised, the JS validation runs and loop should re-run.
I believe ng-init could help...
<ul ng-init="isPageValid='true'">
<li ng-repeat="item in quantityList track by $index" >
<input ng-blur="validateQuantity(item)" ng-model="item.quantity">
</li>
</ul>
Note that it would be better practice to initialise isPageValid in the controller that is in the same scope as your validateQuantity function.
Here is an example of how you could initialise isPageValid in your controller and update the value after each call to validateQuantity...
In your controller:
scope.isPageValid = true;
function updatePageValid() {
scope.isPageValid = scope.quantityList.every(item => item.isQuantityValid);
}
scope.validateQuantity = function(item) {
var qty = parseInt(item.quantity);
item.isQuantityValid = (qty >= 1 && qty <= 200);
updatePageValid();
});

Angular - how to make a an option field (with ng-repeat) depend on previously chosen value in option field?

I have 3 fields.
1st - option field / ng-repeat over available dates
2nd - option field / based on the date chosen by user, I do ng-repeat over quantity. I have tried all different ways but I can't make it depend on the first option field or other things don't work. Any help would be great! Thanks !!
html:
<div class="containerDiv">
<div>
<select ng-model='date'>
<option ng-repeat="availableDateProduct in product " value='{{i}}'>{{availableDateProduct.dateOfActivity}}
</option>
</select>
</div>
<div ng-repeat="availableDateProduct in product ">
<select>
<option ng-repeat='i in quantityLister(availableDateProduct.quantity)' value='{{i}}'>
{{i}}
</option>
</select>
</div>
<div>
<button>Book</button>
</div>
</div>
js:
app.controller('ProductCtrl', function($scope, ProductsFactory, $stateParams) {
ProductsFactory.fetchByTitle($stateParams.title)
.then(function(product) {
$scope.product = product;
})
$scope.quantityLister = function(num) {
var array = [];
for (var i = 1; i <= num; i++) {
array.push(i)
}
return array;
}
})
data:
var products = [
{
title:'Bowling',
description:'Its fun!',
photoUrl:'https://www.1.jpg',
quantity:12,
price:9,
dateOfActivity: '2017-13-07'
},
...
]
Thanks!!
Angular has a directive built specifically to accomplish this task; ng-options.
First, we define an object in the controller that will hold the values selected from the dropdown:
$scope.reservation = {};
Next, we use ng-options on our dropdowns, and use the ng-model property to accept the value selected. In the first dropdown, we take the array of products, display the dateOfActivity for each product, and save the product object to ng-model when selected. (work from right to left in the ng-options definition).
ng-model="reservation.selectedProduct"
ng-options="product as product.dateOfActivity for product in products"
In our second dropdown, you have defined a function to take a number and spread it into an array. We call this function from reservation.selectedProduct.quantity, and then use this array as the basis for the ng-options:
ng-model="reservation.selectedQuantity"
ng-options="num for num in quantityLister(reservation.selectedProduct.quantity)"
Now we have an object which has the selected values for both dropdowns, we just need to change the quantity in the original array on button press. we also want to clear the selections afterwords, to ensure that the user can't accidentally make a duplicate reservation.
$scope.reserve = function (){
$scope.reservation.selectedProduct.quantity -= $scope.reservation.selectedQuantity;
$scope.reservation = {};
};
Here we use the shorthand -= to subtract the selectedQuantity from the selectedProduct.quantity. since selectedProduct is two way bound, the change to selectedProduct is reflected in the original object in the product array as well. However, The quantityLister function isn't dynamic; if we don't reset $scope.reservation, the second dropdown would hold a now invalid number of available reservations.

dynamically change options in dropdown list in angular js

i tried to create dynamically changing dropdown list in angularJS
angulars.js
var option1Options = ["Class","Category","Option","Question","Group"];
var option2Options = [["Group","ProductModel"],
["Class","ProductModel"],
["Class","Group","ProductModel"],
["Group","ProductModel"],
["ProductModel"]];
$scope.myCtrl= function()
{
$scope.options1 = option1Options;
$scope.options2 = [];
$scope.getOptions2 = function(){
var key = $scope.options1.indexOf($scope.child);
$scope.options2 = option2Options[2];
};
}
page.html
<div id="CreateChild" ng-controller="myCtrl">
<select ng-model="child" ng-options="option for option in options1" ng-change="getOptions2()">
</select>
<select ng-model="parent" ng-options="option for option in options2">
</select>
</div>
in angulars.js i was unable to get the index of first dropdown list array. the value of key is assigned as -1 and the option2 is assigned as undefined.
can any one help me with this
I did a small workaround for this requirement, though it is not a straight answer, I believe this would help you...
Add this to your controller...
$scope.getOptions1Idx = function(){
var mySelectedOption = $scope.child;
var i = 0;
for(i=0;i< option1Options.length;i++){
if(option1Options[i]==mySelectedOption){
break;
}
}
return i;
}
and change your getOptions2 function as follows
$scope.getOptions2 = function(){
$scope.options2 = option2Options[getOptions1Idx()];
};
This can be done in much better fashion by avoiding for loop provided if you choose to change your array structure with predefined index some thing like var option1Options = [{id:0,option:"Class"},{id:1,option:"Category"},{id:2,option:"Option"},{id:3,option:"Question","Group"}];
Had a very similar problem with this. In terms of styling I found my way around it by creating a list instead of a select option
<div class='btn-group'>
<button class='form-control col-md-3' data-toggle='dropdown'>
{{value}} <span class='caret'></span>
</button>
<ul class='dropdown-menu'>
<li ng-repeat='type in callType' class='col-md-3'>
<a href='#' ng-click='select(type)'>{{type.name}}</a>
</li>
</ul>
</div>
Then the controller is used to take in the objects, call a method to change each object and then set a default for the drop down list. You can see it at the link below.
http://plnkr.co/edit/nwXmMif8vjj92pQmalb2

Using scope variables with non-form elements

If I have 2 divs (removed ng-click function for simplicity)
<div ng-class="{selected: header.type == 'percent'}" data-type="percent"></div>
<div ng-class="{selected: header.type == 'invisible'}" data-type="invisible"></div>
This will apply the class of .selected to one of the divs, depending on the value of $scope.header.type
However, I also have it so when I click on the div that does not have the .selected class, i remove the selected class from the div that had it, and apply it to the div that was just clicked.
Now, on the controller, how do I get the data-type of the div that has the .selected class?
Basically I'm trying to set $scope.header.type to hold the value of data-type of the div that has the .selected class
Just in case it's needed, here's the ng-click fn (which is not angular-like, but I couldn't find an alternative)
$scope.changeOfferbox = function($event) {
var selected = angular.element(document.querySelector('.selected'))
selected.removeClass('selected')
var clicked = angular.element($event.target).addClass('selected')
}
A simple solution might be to pass the data-type to your click function ; this way, you actually don't even need to manually add/remove classes, the ng-class directives will automatically update when header.type changes :
$scope.changeOfferbox = function($event, localType) {
if (localType !== $scope.header.type) {
$scope.header.type = localType;
}
};
<div ng-class="{selected: header.type == 'invisible'}" ng-click="changeOfferbox('invisible');" data-type="invisible"></div>

How can I update a particular variable in an ng-repeat

I have an ng-repeat that contains items, each of which has an ng-click.
<div ng-repeat="item in items">
<div ng-click="clickMe()">Show Item</div>
<div ng-show="show_item" ng-init="show_item = false>Item 1: {{item.name}}</div>
</div>
$scope.clickMe = function () {
$scope.show_item = !$scope.show_item
};
The problem is that I end up with a list of items that all have the show_item variable. For example, if I end up with a list of 10 items, and I click on the second item in the list, then how can I get angular to know that I want to show the 2nd item, and not one of the other items in the list?
All your items are sharing the scope variable show_item. you have to create this variable for each item
Change your ng-show and ng-init to ng-show="item.show_item" and ng-init="item.show_item = false". Also ng-click="clickMe(item)"
$scope.clickMe = function (item) {
item.show_item = !item.show_item
};

Resources