Angular 1.5 "track by" ruines binding in ng-options - javascript

I need to select option in combobox from ajax loaded data. That data comes as list of objects. The problem is that ng-option compares objects by reference and thus setting model to objects element results in appearing new empty option in combobox instead of selecting correct option.
The known workaround is to use track by expression.
And here is example code:
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.roles =[
{ key:"administrator", value:"ROLE_ADMIN" },
{ key:"operator", value:"ROLE_OPERATOR" },
];
// this emulates data from server
// won't work without 'track by'
$scope.role={ key:"administrator", value:"ROLE_ADMIN" };
});
Template:
<body ng-app="myApp" ng-controller="myCtrl">
0: <input ng-model="roles[0].key" />
<br>
1: <input ng-model="roles[1].key" />
<br>
select role: <select ng-model="role" ng-options="r.key for r in roles track by r.value">
</select>
<pre>selected role={{role|json}}</pre>
</body>
Here another problem arises. When one selects role in combobox and then
changes it's "key" property in textbox, then selected role stays unchanged. So it looks like binding is suddenly gets broken.
https://jsfiddle.net/xLqackxw/8/

from Angular documentation https://docs.angularjs.org/api/ng/directive/ngOptions
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
So:
<select ng-model="role" ng-options="r as r.key for r in roles track by r.value"></select>
'$scope.role' value will be object like { key:"administrator", value:"ROLE_ADMIN" } or { key:"operator", value:"ROLE_OPERATOR" }

Related

AngularJS Select index of selected property

I have a request that returns an array of objects based on a Provider selected. Like this:
data:[
0:
Producto:"Chiken",
Unidad: "box",
PrecioUnitario:"34334",
etc..
1:
Producto:"Chiken",
Unidad: "box",
PrecioUnitario:"200",
etc..
]
I'm displaying the data properly in a <select> tag
What I want is that if the user selects let's say "Carne Asada" all of the other properties of that selected child object are auto-selected on the rest of the fields, i.e:
Unidad text input should be "box" automatically, "precioUnitario" field should be 200.
Or visually:
Another thing is that it should display the value that the object has but it can be edited by the user.
Controller:
$scope.columns = [{colId: 'col1', producto:[], catidad:'', unidades:[], preunit:''}];
$scope.fact = {};
$scope.get_proveedor_prod = function(fact){
var data = {ProveedorID: fact.ProvID};
$http.post(URL + "/api/get_prod_by_provider.php",data).then(function(callback) {
$scope.products = callback.data;
});
}
View:
<md-input-container>
<select ng-model="fact.producto"
ng-options="item.ProductID as item.NombreProducto for item in products"
class="form-control selectformcc" required>
<option value="" disabled selected>Producto</option>
</select>
</md-input-container>
(I'm assuming your data notation is incorrect and that you meant to use an array of objects.)
Bind the select to the whole item instead of to a property of the item:
ng-options="item as item.NombreProducto for item in products" //not ="item.ProductID...
Now fact.producto (select model) is an object and will contain the whole item. In your Unidad text box you can use:
<input type="text" ng-model="fact.producto.Unidad" />
Here is an example with easy to understand data: Working Fiddle

Angular ng-options track by overriding ng-model default option

I have an ng-options iterating over an object, the key of this object is the value I need the ng-options to be set to.
I set the ng-model in my controller to default the select box.
Using track by breaks the ng-model default, however stopping track by removes the issue but introduces another where the default of the select box is no longer the key of the object.
How can I get around this issue?
The HTML I am using is as follows
<select
class="form-control"
ng-change="flightNumber = airline[0]"
name="airline"
id="airline"
ng-model="airline"
ng-options="airline for (airline, flights) in orderedFlights track by airline">
</select>
In my controller I have the following:
var flights = {
"Airline": {
},
"Airline 2": {
},
"-- No Airline Selected --": [
{
unselected: true
}
];
}
$scope.orderedFlights = flights;
$scope.airline = flights["-- No Airline Selected --"];

Element got removed after applying filter

I am applying filters to get the data of a particular field through a dropdown, but when I select any option the filter applied elements get removed. How can I resolve it?
HTML code:
<body ng-controller="MyCtrl">
<div>
<label>Country filter</label>
<input type="text" ng-model="countryFilter" />
<label>Order by</label>
<select ng-model="selectedOrder">
<option ng-repeat="option in options">{{option}}</option>
</select>
</div>
<ul>
<li ng-repeat="detail in details | filter:{loc : selectedOrder}">{{ detail.country }}</li>
</ul>
</body>
JS code:
var app = angular.module('plunker', []);
app.controller('MyCtrl', function($scope) {
// order by options
$scope.options = ['1', '2', '3'];
// all countries
$scope.details = [{
id:1, country:'Finland', address:'Mainstreet 2',detail:[{
loc:'1'
}]
},{
id:2, country:'Mexico', address:'Some address',detail:[{
loc:'2'
}]
},{
id:3, country:'Canada', address:'Snowroad 45',detail:[{
loc:'3'
}]
}];
});
I want to filter through options and loc value. Where am I going wrong?
You don't need to write a custom filter.
Change your filter to: filter:{detail: {loc:selectedOrder}}
I added <option value=""></option> to the dropdown and set $scope.selectedOrder = ""; in order to show all countries by default.
Codepen
filter:{prop:value} returns objects which have property prop at first level, it does not watch in object deeper. (When usual filter without params does it)
Your objects in array details do not have 'loc' property. So nothing fits filter.
You can not filter by exact property of 2nd and deeper levels of object with standard angular filter. Implement your own or change data.

Angularjs Dropdown won't hold value after refresh

I have been working on this way too long trying to figure it out.
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)">
<option ng-repeat="answer in question.answers" ng-disabled="answer.notAnOption" value="{{answer.acode}}">{{answer.name}}</option>
<option style="display:none" value="NONE">NONE</option>
</select>
Then in my js file:
$scope.updateDropDownQuestion = function(question, answer) {
reset(question.code)
$scope.formData["SOLE/SELECTED_QUESTION"] = question.code
$scope.formData["SOLE/SELECTED_ANSWER"] = answer
$scope.formData[question.code+"/"+answer] = true
var questions = $scope.product.questions
for(i=0; i <questions.length;i++){
if(questions[i].code == question.code){
questions[i].sel = answer
break;
}
}
$scope.refresh()
};
the $scope.refresh() is where it changes back. This renders the screen.
no matter what I do it seems to render the previous state and not the current state of the drop down. This is because I am repainting the screen after the drop down changes.
It seems as though the when the screen repaints it is taking the original value first.
Any thoughts on how I can get the value to "stick" once set?
Do I need to fire some event afterwards?
From Angular official site:
Note: ngModel compares by reference, not value. This is important when binding to an array of objects. You might find this helpful to set the default values of your drop down. See an example below.
angular.module('demoApp', []).controller('DemoController', function($scope) {
$scope.options = [
{ label: 'one', value: 1 },
{ label: 'two', value: 2 }
];
// Although this object has the same properties as the one in $scope.options,
// Angular considers them different because it compares based on reference
$scope.incorrectlySelected = { label: 'two', value: 2 };
// Here we are referencing the same object, so Angular inits the select box correctly
$scope.correctlySelected = $scope.options[1];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="demoApp">
<div ng-controller="DemoController">
<div>
<h2>Incorrect</h2>
<p>We might expect the select box to be initialized to "two," but it isn't because these are two different objects.</p>
<select ng-model="incorrectlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ incorrectlySelected.value }}.
</div>
<div>
<h2>Correct</h2>
<p>Here we are referencing the same object in <code>$scope.correctlySelected</code> as in <code>$scope.options</code>, so the select box is initialized correctly.</p>
<select ng-model="correctlySelected"
ng-options="opt as opt.label for opt in options">
</select>
The value selected is {{ correctlySelected.value }}.
</div>
</div>
</body>
Try using ng-options to render option elements.
Something along these lines:
<select class="form-control"
ng-model="question.sel"
ng-change="updateDropDownQuestion(question,question.sel)"
ng-options="answer.acode as answer.name in question.answers">
</select>
It also depends on what updateDropDownQuestion is doing, can you provide that?

ngOptions weird behavior when trying to use resource response as selected item

I tried to solve this over an hour, haven't found anything online.
This is the template:
<select
ng-model="user.platform_id"
ng-options="platform.id as platform.title for platform in platforms"
id="platform_id" class="form-control">
</select>
and this is the controller :
$scope.platforms = platformsEntity.query();
// Resource object coming from UI Router resolve, already fetched with user info
$scope.user = userEntity;
the platforms resource response return the following format:
[ { id: 4, title: 'platform1'}, { id: 5, title: 'platform2' ]
the user is same, resource object with platform ID
{ id: 3, name: 'foo', platform_id: 5 }
This way I can see all the platforms in the select box but it's not getting selected by the ngModel value (user.platform_id)
The thing is that when I use plain object instead of resource:
$scope.platforms = platformsEntity.query();
$scope.user = { platform_id: 5 } ;
It is getting selected correctly ...
Update
i replicated the behavior i am looking for in ng-repeat:
<select ng-model="user.platform_id" id="platform_id" class="form-control">
<option
value="{{ platform.id }}"
ng-selected="user.platform_id == platform.id"
ng-repeat="platform in platforms"
>{{ platform.title }}</option>
</select>
It's not about using a resource, the problem with programmatic selection of ng-options is that the ng-model value should refer to the same object as in the ng-options. In order to initialize the selection, first make sure that the platforms array is populated (query might be async?), then loop through them, and set the id object of the platform of your choice as the platform_id object of the user.
Try something like this. Tell angular what you want to track the value by.
<select
ng-model="user.platform_id"
ng-options="platform.title for platform in platforms track by platform.id"
id="platform_id" class="form-control">
</select>

Categories

Resources