Having a default value in ng-options in angularjs but also having persistence when we get back to the form again - angularjs

My current scenario is i query a service and bring an array of values and display it in dropdown in AngularJS using ng-options. The problem is i need a default value at the top of the dropdown somthing like "Select from the list".
I have done that using
<option value="">Select from the options</option>
the problem is i also need to persist the data when i select suppose first value in the dropdown and go to some other page for sometime and come back to the same page which has that dropdown. That time i again need to see the first item selected and not the "Select from the options" thing.
How can i add this text "Select from the options" to the array which comes after querying a service and populates the dropdown also maintaining the persistence using ngModel.
Thanks,
MK

Assuming that the "other page" is still in the same (single-page) Angular application, you can store the selection in a factory and when you come back to the page, initialize the ngModel object (in the controller) by reading it from the factory. There are many ways, but this is one of the usual basic patterns in Angular.
If the visit to the "other page" causes Angular to be reloaded, one typical approach is to store the settings in local storage.

Related

AngularJS - memorizing chosen values in form after returing from some special state (view)

I build some form analogously to:
http://tutorials.jenkov.com/angularjs/forms.html
It means that I also use ng-model as chosen value. These values are retrieved from database - there are multiselect options.
<form>
<input type="text" name="firstName" ng-model="myCtrl.firstName"> First name <br/>
<input type="text" name="lastName" ng-model="myForm.lastName"> Last name <br/>
</form>
Controller {
constructor() {
this.firstName = getFirstNameFromDatabase();
}
}
It is sketch of my code - I wouldn't like to show it here.
It is working ok - values are retrieved from database and displayed as proposition in form.
My issue is following:
Let's assume that someone type in this form "abc". Then, someone click button next (it direct to another state, user is directed to another view - lets denote it X).
User can return from X view with back button. I would like to display "abc" (so my app should memorize chosen values).
However, if user type value "abc" and return to menu (or another else state (view) - different from next button) - in this case value shouldn't be memorized.
Can you give me some clues ?
Since you're actually switching pages in your application, you're going to have to put their content in some sort of persistent storage. A couple ideas pop into my head.
Temporary Browser Storage / Cookies
Server-side storage in a Database or Cache
Either way, you'll need to store the data whenever the user manipules the values. And when they switch pages, choose whether to clear the data or not based on whether it's your special view.
Or another idea is to use an angular function to change the url (rather than a simple anchor). Then in that function you can persist the data before switching to your view. But if they go to a different page, it won't get saved. This only works if they navigate based on your page's links.
Usually this sort of thing is accomplished using a single page which includes both your original view and the next view. You can swap out the content using JS so the user doesn't know the difference. So that's still an option too.

Validation Issue in IE 11 when same ng-model in multiple form set to required

The application I am working on has multiple tabs, each tab contains a form with ng-submit. And they share some common fields for example: selectedService.
It's been set to required in both forms. However updating it in one form then switch to another form, Chrome wouldn't complaint it's required since it already has value, however IE 11 complaints that it's required although it already has data entered and angular indicates that it's valid as well.
Is there anyway that I can update IE to let it know that this model has been updated and it has value? Or it's the form needs re-validation?
---------------------Update--------------
I am finally able to replicate it: http://plnkr.co/edit/Gjphya?p=preview
So if you select a value in the first dropdown and click submit in the second row, it says it's required. This only happens in IE, not in Chrome or other browsers.
And I think the problem is around this line:
$scope.selectedService = null;
Thanks!
All I need to fix is to add this line in the select tag:
<option value="">Please Select...</option>
If I init the ng-model in controller, it also fix the issue, however sometimes it causes unexpected issue if the dropdown is binded to an array instead of object collection.

Angular UI bootstrap: Type ahead select multiple

I am using angular UI bootstrap type-ahead directive for type-ahead in a form
http://angular-ui.github.io/bootstrap/
I am fetching the records from remote server via $http service. It is working fine.
However I can select only one element from list at a time.
I want to select multiple values from the list and show all currently selected element in input field with a remove button just like tags for SO. The selected tags are stored in angular array model.
How to achieve this ?
I have read documentation for Angular UI bootstrap but I am not able to find anything.
This guy made a directive for this. Should do exactly what you want and it's even using the ui-bootstraps typeahead.
https://github.com/mbenford/ngTagsInput
The best solution I have found so far is io.select
it does exactly what you require, multi-select typeahead.
and the markup is neat and clean too e.g:
<oi-select
oi-options="list.id as list.description for list in lists"
ng-model="tags"
multiple
placeholder="Select">
</oi-select>
This component is also compatible with bootstrap and the new bootstrap 4.
In js file :
To list all selected items, use $item with typeahead-on-select and push to an array for ex.evtMem. delete fn to delete selected item.
HTML :
Use table to list all array values using ng-repeat. Addition to that add remove glyphicon image and function to delete corresponding item.

Initializing ngModel with data - AngularJS Bootstrap bs-select

I am maintaining a site that allows users to create a profile of sorts that will allow them to broadcast activities to a feed. I implement ng-grid to keep track of all the profiles that are created, and have created two buttons that allow users to create/edit these profiles. My only problem right now is, when users select a row on the grid and attempt to edit that specific row, the drop-down menu is not auto-populated with the data from ngModel.
This is the part of the form I am having trouble with:
<select ng-model="source.canSendTo" ng-options="value.name for value in sourceCanSendTo" data-style="btn" bs-select></select>
And within the controller, I have sourceCanSendTo defined as:
$scope.sourceCanSendTo = [ {"id":"abc", "name": "ABC"}, {"id":bcd", "name": "BCD"} ... ];
On row selection, I simply set source = the selected item, and console.logs show that all the data is there. The other parts of the form are being populated properly (mainly s), and console.log($scope.source.canSendTo) shows that the original data is there, it's just that select is defaulted to being blank...how would I go about trying to pre-select certain elements on the drop-down select I currently have?
For example, if the profile has 'abc', 'bcd' selected, how can I make it so that when I edit that profile, the drop down box shows 'abc,bcd' instead of just "Nothing Selected"?
Edit: I previously responded to a comment inquiring about bs-select, saying that it simply controlled some CSS elements of the drop down box - seems like this is completely incorrect after a quick google search when everything else led to dead ends. Does anyone have any idea how to properly initialize the model with data so that when I preload my form, the 'can send to' drop down select actually has the selected options selected, as opposed to saying "Nothing Selected"? Thanks in advance for all help!
As you are binding source.canSendTo to the name (value.name) of sourceCanSendTo then you just need to initially have an structure binding the names which had been saved, something like this:
source.canSendTo = ['abc', 'bcd']; //And all the selected values
So you need to construct your source.canSendTo property to this structure.
PS: If you show how you bring your data from the server, I can help you to construct the source.canSendTo property.
$scope.canSendTo must be initialized with a reference to the selected option.
var initialSelection = 0;
$scope.source = { canSendTo : [ {"id":"abc", "name": "ABC"}, {"id":bcd", "name": "BCD"} ... ] };
$scope.canSendTo = $scope.source.canSendTo[initialSelection];
Finally found out what was wrong with my code - seems like the data being stored in the model wasn't the same as what was in ngOptions, played around a bit with ngOptions and managed to get something that works. Working snippet of code:
<select ng-model="sendTo.name" ng-option="value.name as value.name for value in sourceCanSendTo" data-style="btn" multiple bs-select>
(Realized that the variable being used for ngModel was a fairly ambiguous in terms of naming convention, changed it)

web2py - Dropdown menu

I'm trying to have a dropdown menu for the user to select the database table. I have defined few tables in db.py and I want the user the to select a particular table from a dropdown menu and insert entries. Right now I use SQLFORM:
def index():
form=SQLFORM(db.selectedtable) #want to change the table name#
if form.process().accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill out the form'
return dict(form=form)
I need the user to select 'selectedtable' value from a dropdown list that shows all the available tables in the DB. I do not necessarily want to retrieve the table values from DB. I am OK with defining a list with the available tables and the dropdown menu can pull the table names from that list.
So far I only found IS_IN_DB to automatically create a dropdown and PluginDropdown() but that does not serve my purpose. If soemebody can direct me to the proper way of handling this task I'd be really thankful.
Regards.
Update:
After Anthony's suggession I tried the following with , as I'm not that familiar with JS.
{{extend 'layout.html'}}
{{select='NONE'}}
<form>
<select>
{{for item in TOOLS:}}
<option value="{{select=item}}">{{=item}}</option>{{pass}}
</select>
<input type="submit" value="Go!"/>
</form>
<h2>Input form</h2>
{{=form}}
<h2>{{=select}}</h2>
As you might see this doesn't work properly. What I tried to do is to get the user chose value to 'select' variable. But it doesn't work. It always gets the last element in ITEMS (this list is defined in db.py). My next option would be to be call another controller function, passing the user selected value as an argument. Then it can prepare the form with the passed value and send to a view to display
<h2>Input form</h2>
{{=form}}
But I'm not sure how I can assign the user chosen value to an argument and then call another controller function with that arugument value.
If you have any suggestion how I can modify this to get the user chosen value thats very much appreciated. Thank you.
You could create a <select> element listing all the tables, and then load the form associated with the selected table as a web2py component via Ajax. In the view of the main page (e.g., /views/default/index.html):
<script>
jQuery(function() {
jQuery('#table').change(function() {
web2py_component("{{=URL('default', 'form.load')}}" + "/" +
jQuery(this).val(), target='form')
})
})
</script>
{{=SELECT('Select a table', *db.tables, _id='table')}}
<div id="form"></div>
And in a controller (e.g., default.py):
def form():
if request.args(0) in db.tables:
response.generic_patterns = ['load']
return dict(form=SQLFORM(db[request.args(0)]).process())
else:
raise HTTP(404)
Note, db.tables is a list of all the tables defined on the db connection object -- it is used in the SELECT() helper in the view to generate a <select> list of all the tables. The script in the view registers a jQuery event handler that fires whenever a different table is selected from the dropdown. The handler calls the web2py_component() function (which is in /static/js/web2py.js), which loads the form component via Ajax into the div with id="form". It appends the value of the selected table to the URL.
In the controller, the form() function checks for the db table name in request.args(0). It then sets response.generic_patterns so the "generic.load" view will be allowed (by default, generic views are only enabled for local requests). Alternatively, you could define your own "form.load" view, or even use a different extension (e.g., "form.html").
Because the form is loaded as a web2py Ajax component, the form submission will be trapped and submitted via Ajax as well, so it will not result in a full page reload.

Resources