ng-repeat with ng-selected - javascript

I am trying to figure out how to generate list of option elements using ng-repeat, but one of them to be marked as the selected option on load.
After googling, what I found is this base, which I modified by adding the selected property to the data objects
https://plnkr.co/edit/7g4MeAQnG4PzpnrebBGc?p=preview
However, it seems that ng-selected="option.selected == true" has no effect :(
Why? I also have the more complex example here: http://jsfiddle.net/ej5fx3kr/14/ which works, although I am not sure what is the difference, or what is the model here used for (note: changing the model name from "program" to anything, it still works... so not sure what is the purpose).
Bonus points: How do I debug code in AngularJS in directives? Like experiment in debug mode line by line to actually see what are the variable values in that particular scope, what is available to use, etc...
My ultimate goal in this question, is to load list of values via ajax on page load in the controller, IF there is a routeParam in the URL, find it in the list of loaded values, and add selected attribute, then set selected=true in the generated HTML on page load, otherwise not pre-select anything in the populated select box on the page load, so this is why its important for me to understand this on the simplest example before trying to plug this in.
Thanks!

The "Angular Way" to handle this is to use ng-options instead of ng-repeat, and then simply set the model equal to the default value on controller load.
For example:
<select ng-options="option.name for option in data.availableOptions"
ng-model="selectedItem"></select>
$scope.selectedItem=$scope.data.availableOptions[2];
For a more advanced case, where your ng-model might not be the object in the array, but a single property, you can use a modified version of ng-options:
<select ng-options="option.id as option.name for option in data.availableOptions"
ng-model="selectedId"></select>
$scope.selectedId = '2';
Here is a modified version of your plunker showing these different possibilities: https://plnkr.co/edit/xzYmXf8C3WuZaelwj5hO?p=preview

Using ng-selected = true inside ng-repeat would solve this .
However be sure of the data that you call in ng-repeat.For additional debugging and experiment line by line use chrome debugger .go to source tab and set break points on the js lines that you need to debug.This will let you debug line by line by pause and play . Hope this helps.Thanks

Related

How can I manipulate HTML elements which are added during the runtime?

The code im working on first makes a call to the database. Through this call, it is determined wether there are available workstations in the office or not.
If there are available workstations, "option" elements are added to a "select" element. This is achieved via jquery:
$('#idofselectelement').html(data)
Where "data" represents the markup to be inserted into the "select" element.
Now, my problem is that I'm trying to implement some code which checks wether your "favorite workstation" is available in the selected timeframe and then automatically preselects the respective workstation from the dropdownmenu in the "select" element. Everything is working so far, except for the selection of the workstation from the dropdown menu :/
The part of
I'm rather new to programming with javascript and the HTML DOM, so I'm not sure whether the fact that the options im trying to chose from are added during the runtime?
The code I've tried to manipulate the dropdown menu with is like this:
$('#idofselectelement').val(favoriteworkstation);
However, as I said, this doesn't work.
I've also already tried to output (console.log) the select element's length property right after the code which adds the markup with the available options has run.
But according to the output Im getting, the length is zero Oo
However, the dropdownmenu is definitely being created AND I can indeed manipulate it, but unfortunately not in the way I want to.
If I add an onclick event which sets the value of the respective select element, then the value in the select field indeed changes to the value specified in the event handler.
So I wonder why I can't have the favorite workstation preselected after the timeframe was chosen...
EDIT:
For further insight into the problem, I'm adding a bit more code here.
This is what the HTML Select element looks like BEFORE anything is added during the runtime:
<label for="#sitz">Sitz Nr.</label>
<select type="text" class="form-control" id="sitz" name="sitz" value="">
the markup which is added during the runtime
<option>workstationvalue</option>
<option>workstationvalue</option>
//and so on, depending on the situation...
This is a timing issue.
The js trying to find the element is faster than the actual add of the element to DOM.
Can you describe what you want to do? You might be able to do that before adding the element to DOM.
Editing before adding to DOM is possible if you convert your String to an jQuery object
var $jqueryObject = $(data);
$jqueryObject.find('.classYouSearch').val(value);
$('.whereToAd').html($jqueryObject);

SET the value of a Shopify Option Selector / change selected variant via javascript

I am building a custom "subscription builder" where customers select options, proceed to the next step and at the end click checkout; their options reflected in the variant selected.
The way Im going about this is by hiding shopify's selectors and setting them manually using $().val(); This accurately changes the selectors (checking in inspector), but Shopify does not recognize these changes for some reason and so the product added to the cart is the default. I am obviously missing something - is this even possible?
[Code Redacted for uselessness]
Thank you!
Basically,
Shopify's option_selection.js controls this and has a "Product" and "OptionSelector" object.
OptionSelector has a function selectVariant(id, selector) that will properly set it given you have the full variant identifier.
In your product_form.liquid you will see a place that does new OptionSelector(args). You simply save what it returns, i.e.
selector = new OptionSelector(...);
then you can do
selector.selectVariant("123456789", selector);
This will properly set the variant for the checkout button. You can then either hide the 'shopify' selectors with css / js or keep them or modify the option_selection.js code yourself by downloading from here.
Furthermore, I've discovered more useful things one can do:
selector.selectors[index].element.value {get; set;} //much cleaner method of accessing selector elements
selector.product.getVariant(selector.selectedValues()).id // gets the variant id for you so you do not need to hardcore them in
EDIT: Dave has kindly pointed out that
$(element).val(newValue).trigger('change');
Would have done what I wanted, but points out (and I agree) that using OptionSelector is more of a robust method.

ng-model scope not available while using with ng-options

I am just trying to implement a simple drop down and here is my code
<select ng-change="selectTestSuite();" ng-model="testCase" ng-options="testSuite.TEST_NAME for testSuite in publicTestCase"></select>
In the controller when I am trying to print value of testCase in console it is giving undefined. But When I try to print id of testCase using
{{testCase.TEST_ID}}
It is giving me id. I have also checked by using $watch
$scope.$watch('testCase',function() {
console.log($scope.testCase);
});
Unable to figure out where I am making mistake.Appreciate any help.
I think no problem with ng-options.
Actually ng-options maps the "testSuite.TEST_NAME" as model to ng-model.
Ensure the "testSuite.TEST_NAME" is available in "publicTestCase" collection (Whether it is undefined).
You are binding the testCase to testSuite.TEST_NAME.
Your ng-options should look like this:
<select ng-change="selectTestSuite()" ng-model="testCase" ng-options="testSuite as testSuite.TEST_NAME for testSuite in publicTestCase"></select>
The model gets bind to the value of testSuite from the records in the publicTestCase array and for each of the testSuite you want the testSuite.TEST_NAME to be shown as the options text.
enter image description here
Note:- Please find the image link.image contains code
ng-repeat directive repeats a block of HTML code for each item in an array, it can be used to create options in a dropdown list, but the ng-options directive was made especially for filling a dropdown list with options, and has at least one important advantage:
Dropdowns made with ng-options allows the selected value to be an object, while dropdowns made from ng-repeat has to be a string.

AngularJS model does not update after manual change of option

I have a problem with AngularJS model. Currently I have two select tags and I fill it by some async action then I just set select tag model by received data. Everything works well but if I change select tag (option) manually then model can't be changed anymore by this async actions - script keeps model picked by me manually - I am sure that I assign proper data to model from server response, because it works untill I don't change it manually...
<select ng-model="sModel" ng-change="changeAction(sModel)" name="sList" id="sList" ng-options="s.name for s in sList track by s.sId"></select>
(second select looks like above).
If someone have some idea why ngModel can't be updated after manual changes, please reply :)
You must be using ng model with direct variables. When using ngmodel with html input types use object types in ng model else value does not reflect.
$scope.req={value:""};
in html use
<select data-ng-model="req.value"></select>
Weird but I fixed it - It was because 'select' was wrapped by div which had ng-controller. Controller contains actually one action with change select option. After remove this ng-change it didn't help but removing whole controller declaration did..
<div ng-controller="sController">
<select ng-model="sModel" ng-change="changeAction(sModel)" name="sList" id="sList" ng-options="s.name for s in sList track by s.sId"></select>
</div>
Someone can explain me this anomaly ? ;/ Model always was changed in main/common controller (parent) where also was initially created.
http://jsfiddle.net/nkr33bo0/

Select2 loading page with existing value

Trying to load an edit profile page for a musician site. There is a select2 box that lists the instruments that the user plays, and it pulls this information from the database. But I can't figure out how to get the existing instrument list to display on the select2 on render, it always displays as an empty select2 box (the actual search and select functionality of the box works).
(this is coffeescript in meteor)
On render, it runs:
populator = Meteor.user().profile.instrumentsPlayed
$("#e9").select2()
the populator variable defines properly and has a value of
["acoustic guitar", "piano", "ukulele", "piano"]
I've tried many variations including:
$("#e9").select2("value", populator)
None of the variations worked, and I have a hard time finding and implementing the exact thing I need from the select2 documentation... can someone point me in the right direction?
Summary: need to load select2 box with existing data instead of just empty select2 box
See the documentation here: http://ivaynberg.github.io/select2/#programmatic
They use "val" and not "value" to programmatically set the values.
Try this:
$('#e9').select2();
$('#e9').select2('val', populator);
edit:
Perhaps the confusion was the select2() should be called before select2("val",...).
Here is a jsfiddle http://jsfiddle.net/JFMbt/ showing both methods (comment out one of them)

Categories

Resources