angularjs ng-model(s) $scope - angularjs

I'm quite new in AngularJs, I just started to learn this World today. I think I got the point, but I do not understand the next problem.
I have a site which contains a lot of select input fields. I will explain my problem with two select fields
********** THE HTML FILE *************
enter code here
<div id="FormContainer" ng-app="PermissionsApp">
<div class="permission_container" ng-controller="PermsCtrl">
<select id="select_all" ng-model="select_all_var" ng-change="UpdateAll()">
<option value="" ng-hide="true">-</option>
<option value="0">-</option>
<option value="n">no</option>
<option value="a" ng-selected="true">all</option>
<option value="g">group</option>
<option value="o">own</option>
</select>
<select id="select_1_1" ng-model="select_1_1_var" ng-change="Update(1, 1)">
<option value="" ng-hide="true">--</option>
<option value="n">no</option>
<option value="a" ng-selected="true">all</option>
<option value="g">group</option>
<option value="o">own</option>
</select>
</div>
</div>
************** THE JS FILE **************
enter code here
var permissionsApp = angular.module("PermissionsApp", []);
permissionsApp.controller("PermsCtrl",['$scope', function($scope) {
$scope.UpdateAll = function () {
console.log($scope.select_all_var + " - " + $scope.select_1_1_var);
}
$scope.Update = function (modul_id, action_id) {
console.log($scope.select_all_var + " - " + $scope.select_1_1_var);
}
}]);
OK ...
FIRST ISSUE
IF I change FIRST the select_all field after page reload, I get the next on the console: g - undefined
After that I change the select_1_1 field, I get the next on the console: g - g
SECOND ISSUE
If I change FIRST the select_1_1 fieldl after page reload I get the next on the console: undefined - g
After that I change the select_all field, I get the next on the console: g - g
SO ... it seems for me the variables can be seen in the $scope just after the change event .... do I need to declare the variables first time, or what's the problem? But I there are about 200 select fields on the page ... I do not want to declare them one by one.
Thanks for your answers in advance!
FF

So there are 2 ways to fix this:
ng-init
You can initialize your model to the desired value using:
<select ng-model="select_1_1_var"
ng-init="select_1_1_var = 'a'">
I don't use ng-selected much so I'm not familiar with its inner workings, but I would make an educated guess that this works solely on the UI and that it argues with other directives regarding initializing model values.
example - https://plnkr.co/edit/eO60jeXIKlDhAFuopnUc?p=preview
ng-options
So there has been a lacking feature (in my opinion) that you couldn't initialize a select control with a pre-existing model value when declaring your option elements. This is especially problematic when trying to use ng-repeat. It is recommended that you use ng-options and set your options via the controller as well as initialize your model values there:
<select id="select_all"
ng-model="select_all_var"
ng-options="opt.value as opt.name for opt in opts"
ng-change="UpdateAll()">
</select>
example - https://plnkr.co/edit/M4qZEL4Y8EfRtabfSN8a?p=preview
bonus
If you want to display an empty option without muddying up your options array, please visit my answer here - Why does AngularJS include an empty option in select?

Related

Angularjs ng-model - convert string to number

I see a blank drop down, which I suspect is due to an additional option that gets injected. If I am able to remove this additional option generated, I think, my problem will be solved.
Auto-injected Option:
<option value="? number:1 ?" selected="selected"></option>
My View:
<select id="myValue"
ng-model="myObject.value"
ng-change="foo()">
<option value="0"
localize="MyValue0"
ng-selected="myObject.value === 0"></option>
<option value="1"
localize="MyValue1"
ng-selected="myObject.value === 1"></option>
</select>
How can I conver myObject.value to number? I have tried ng-Model = "parseInt(myObject.value)" and ng-model = "myObject.value | number". Both throw a nonassignable element error. I am using Angularjs 1.6 and moving away from directives, so creating angular.directive function may not be an option
I believe it's Angular best practice to use the ngOptions directive, documented here.
Also, regarding the first option being <option value="? number:1 ?" selected="selected"></option>, I suspect that's because the initial value of myObject.value doesn't match any of the possible options values.
Try this:
<select id="myValue" ng-model="myObject.value" ng-change="foo()"
ng-options="item for item in options">
<option value="" disabled selected style="display:none;">Placeholder</option>
</select>
JSFiddle here showing that myObject.value is a number.
Updated JSFiddle to showcase the dropdown without a placeholder.

AngularJs - Dependent Select - How to get the picked value

so I have two dependent select, one for states and the other for cities. It works fine but I can't get the value picked in the first select. I tried everything, the only result I got was the list of all the cities. What I need is which state picked.
My code:
<label>States</label>
<select id="provincia" class="form-control" ng-model="ciudades" ng-options="provincia for (provincia, ciudades) in provincias">
<option value=''>Elegir</option>
</select>
<label>Cities</label>
<select id="ciudad" class="form-control" ng-disabled="!ciudades" ng-model="modelciudad" ng-options="ciudad for ciudad in ciudades" required>
<option value=''>Elegir</option>
</select>
My list is something like this:
$scope.provincias = {Florida:['Miami', 'Orlando']}
I try using ng-model on Option tag but with no result.
Thanks

ng-model not working with ng-repeat

I'm trying to figure out why the ng-model is not working with the ng-repeat.
There is my code:
$scope.availableCountries = [];
APIUtility.getCountries().then(function(data){
$scope.availableCountries = data;
$scope.filters.country = "AZ";
});
<select id="eventprice" class="searchpage_select" ng-model="filters.country">
<option value="all">show all</option>
<option ng-repeat="countries in availableCountries" value="{{countries.country_iso}}" ng-class="{'element_selected' : filters.country == countries.country_iso}">{{countries.name}}</option>
</select>
where:
availableCountries is an object from an API call (well formed, trust me)
$scope.filters is an object containing a lot of filters (including country)
The problem is that if i change the ng-model before or after the API call, the select statement is not updated, i think that if i update the scope before angular has the time to execute his ng-repeat, ng-model stop working and will not update the field.
i added the ng-class to prove that filters.country has the right value (ng-class statement returns true when needed and add the class in the right place, so filters.country contains the right value).
I don't know if i was clear enough. Thanks all for your time!
Use ng-options instead of an ng-repeat on an option field.
<select id="eventprice"
class="searchpage_select"
ng-model="filters.country"
ng-options="country.country_iso as country.name for country in availableCountries">
<option value="all">show all</option>
</select>
Problem is in
$scope.filters.country = "AZ";
Try this updated jsfiddle
http://jsfiddle.net/HB7LU/15021/

select ng-options issue in angular js

I am trying to choose the leader of a team using 'select' ng-options feature.
Student object:
student{
name:String,
status : String
}
My code to select team leader is as below.
<select ng-model="class.team.leader" ng-options="student._id as student.name for student in curTeam.students">
<option value="">Select leader</option>
<option value="class.team.leader">{{class.team.leader.name}}</option>
</select>
The 'select' is storing the values correctly into the appropriate model values. But, the select is not displaying the model value properly when I go to the page view. But this code is fine for saving the details.
Requirement:
if there is no value for the model, then option value="" ==> 'Select leader' is displayed by default. if else, it should display the 'class.team.student.name'
Some one please let me know where I went wrong.
Thanks.
HTML:
<select ng-model="class.team.leader" ng-options="student._id as student.name for student in curTeam.students">
<option ng-show="!weHaveALeader" value="">Select leader</option>
<option ng-show="weHaveALeader" value="class.team.leader">{{class.team.leader.name}}</option>
</select>
JS:
$scope.weHaveALeader = false;
$scope.$watch('class.team.leader', function(new, old) {
$scope.weHaveALeader = true
}
You could remove the second option tag, that seems unneccessary.
I've put your code into a plunker http://plnkr.co/edit/OZCal9ZkCQeqnQJY0WP9?p=preview and it seems to work fine.
<select ng-model="class.team.leader" ng-options="student._id as student.name for student in curTeam.students">
<option value="">Select leader</option>
</select>
<div><b>Team Leader:</b> {{class.team.leader}}</div>
If that isn't what you want, please give more detail of what are missing.
The correct method to use select ng-model is as below.
Select leader
{{class.team.leader.name}}
This has solved the issue of displaying on the page reload.

Angularjs ngOption with array

I want to add an html select with options AM,PM with angularjs,
what i need is having the key and the value of the option be the same :
<option value="AM">AM</option>
<option value="PM">PM</option>
My html looks like this
<select ng-model="ampm" ng-options="k as v for (k , v) in ampms"></select>
and my controller looks like
$scope.ampm = (new Date().getHours()) >= 12 ? 'PM' : 'AM';
$scope.ampms ={"AM":"AM","PM":"PM"};
and every thing working fine.
My question is why i cant have the same thing when i used an array (i tried all the options in the ng-options)
as this
$scope.ampms =["AM","PM"];
what ever i do i always get this
<option value="0">AM</option>
<option value="1">PM</option>
What i want is using an array like above with the option has the key and the value the same.
With AngularJS, you don't need to worry about what the value of the option is. All the selects I've seen with ng-options have values of 0 through whatever. If you're just looking for a dropdown with the two options, it can be as simple as
<select ng-model="ampm" ng-options="currOption for currOption in ['AM', 'PM']"></select>
See http://jsfiddle.net/EyBVN/1/
This is is a default behavior of ng-options in Angular. If you do not specify a key name, angular will automatically choose to use the index rather than a key. The code that does that can be seen on line 405 in /src/ng/directives/select.js on Angular's Github repository.
It can't even be forced by "value as value for (index, value) in values".
But as dnc253 just beat me to the punch with his answer (it showed up while I was typing)... you don't have to worry about it, Angular does it all for you automatically.
I did find a way to place specific data in the value of the options for a select. You have to add an ng-repeat attribute to the option tag inside the select tag:
<select id="{{question.id}}" name="{{question.id}}"
class="{{question.inputclass}}" ng-required="question.required"
title="{{question.title}}">
<option value=""></option>
<optgroup ng-repeat="group in question.data" label="{{group.group}}">
<option ng-repeat="item in group.data" value="{{item.value}}"
ng-selected="{{item.value == question.defaultValue}}">
{{item.description}}
</option>
</optgroup>
</select>
As a bonus, I left the option group tags in place to serve as an example for everyone.
The question.data JSON is:
[
{"group":"Canada","data":[{"value":"Ontario","description":"Toronto"},
{"value":"Quebec","description":"Quebec City"},
{"value":"Manitoba","description":"Winnipeg"}
]
},
{"group":"Mexico","data":[{"value":"Jalisco","description":"Guadalajara"},
{"value":"Nayarit","description":"Tepic"}
]
},
{"group":"United States of America","data":[
{"value":"Alabama","description":"Montgomery"},
{"value":"Georgia","description":"Atlanta"},
{"value":"Mississippi","description":"Jackson"},
{"value":"Louisiana","description":"Baton Rouge"},
{"value":"Texas","description":"Ausint"}
]
}
]

Resources