hiding an option in ng-options - javascript

I'm pretty new to Angular and trying the ng-options. In my controller, I have:
$scope.permissionLevels = [
{ value: "ROLE_READ", text: "Read Only" },
{ value: "ROLE_WRITE", text: "Write" }
];
In my template, I have:
<select ng-options="permissionLevel.text for permissionLevel in permissionLevels"
ng-model="selectedValue"></select>
Depending on the view, I want to hide either Read or Write. So in my controller, I have another flag that indicates what view it is. Before I used ng-options, I had a normal select drop down and did something like this:
<select>
<option>Read Only </option>
<option ng-show="shouldShowWrite">Write </option>
</select>
Is there a way to do this with ng-options? Thanks.

You could use a filter in the ngOptions expression:
<select ng-model="selectedValue"
ng-options="permissionLevel.text for permissionLevel in
permissionLevels | filter:shouldShow">
</select>
and define the shouldShow() function to $scope in the controller:
$scope.shouldShow = function (permissionLevel) {
// put your authorization logic here
return $scope.permission.canWrite || permissionLevel.value !== 'ROLE_WRITE';
}
For the full example see: http://plnkr.co/edit/8FkVktDXKGg3MQQawZCH

Consider ngRepeat for that level of control. I don't think it's possible with ngOptions.
<select ng-model="selectedValue">
<option ng-repeat="permissionLevel in permissionLevels" value="{{permissionLevel.text}}" ng-show="shouldShowWrite(permissionLevel)">
{{permissionLevel.text}}
</option>
</select>

Plaese check below code, it may help you to solve the problem!!
<select>
<option>Read Only </option>
<option ng-show="selectedValue.value=='ROLE_WRITE'">Write </option>
</select>

Related

Blank select option #ngValue

How can I avoid blank option in the form output?
<select class="form-control" ng-model="item.type" >
<option ng-value="0">Real</option>
<option ng-value="1">Fake</option>
<option ng-value="2">Both</option>
</select>
item.type is set in the controller
The issue slightly different from what I saw in similar topics because of usage of ng-value and the fact, that value of item.type is already set
Edit: Changing ng-value to value solved the issue.
How is item.type set in the controller?
The blank line is the current value of item.type. If you set it as an object in the controller, it's normal to be shown that way. Try setting it to one of the 3 choices you have like this:
angular.module('yourModule').controller('ctrl', function($scope)){
$scope.item = {}; //edited
$scope.item.type = "1"; // or 2, or 0
}
This is how angular handles two-way databinding. If the value of your item.type does not match any of the options, it is normal to add another blank line.
EDIT:
<select class="form-control" ng-model="item.type" >
<option value="0">Real</option>
<option value="1">Fake</option>
<option value="2">Both</option>
</select>
The problem of blank option is due to the ng-model is not matching with the ng-option values. Could you just print the value of item.type in view using {{item.type}}.
Make the following changes.
In controller set the item.type as
$scope.item = {};
$scope.item.type = "1";
make the following changes in html.
<select class="form-control" ng-model="item.type" >
<option value="0">Real</option>
<option value="1">Fake</option>
<option value="2">Both</option>
</select>

ng-selected not working

My problem is that ng-selected is set as true but the option is not getting selected
This is my controller code
.controller("PendingInvoiceCtrl", function($scope, $location, safeApply, dataService) {
var userData = dataService.data();
var mauth_token = userData.mauthToken;
var mauth_acntId = userData.thisApartment.account;
var apt_id = userData.thisApartment.id;
$scope.house_list = userData.thisApartment.house;
$scope.selectedHouseId = $location.search().houseId;
console.log($scope.selectedHouseId);
});
This is my HTML code
<select ng-model="selectedHouseId">
<option ng-repeat="house in house_list" ng-selected="{{ house.house_id == selectedHouseId }}" value="{{ house.house_id }}">
{{ house.house_display_name }}
</option>
</select>
And below is my data format
{
house:[0]:{
house_display_name: "paras, 101",
house_id: "520755"
}
}
The ng- attributes don't need the extra curly braces. Try:
<option ng-repeat="house in house_list" ng-selected="house.house_id == selectedHouseId" ng-value="house.house_id">
{{house.house_display_name}}
</option>
A better approach would be to use the ng-options possibility of the select tag. This would result in:
<select
ng-model="selectedHouseId"
ng-options="house.house_id as house.house_display_name for house in house_list">
</select>
And then you don't need to manually worry about the selected attribute for the options, as it will select the one depending on the value of the model.
Your option tag should be:
<option ng-repeat="house in house_list" ng-selected="house.house_id == selectedHouseId" ng-value="house.house_id">
if you use ng-Selected and ng-Model together was never really specified. It looks like at some point ng-Model took priority over ng-Selected.
I recommend you to use the Angular Directive ng-options.
<select ng-options="house.house_id as house.house_display_name for house in house_list" ng-model="selectedHouseId"></select>
Associated plunker: http://plnkr.co/8LGz5o0d2gDRoRHYr4pQ

Can't set select value from my controller, Angular JS

From this example
I'm trying to set the select value from my controller and this doesn't work for me even when I set the id as explained in many questions here. The only difference is that I have a default value set with ng-init. How do I set the value from the controller?
DOM:
<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)">
<option value="0">-- All orders --</option>
<option ng-repeat="obj in orders" value="{{ obj.id }}">{{ obj.name }}</option>
</select>
JS inside a function:
$scope.orders = data;
$scope.storeorder = parseInt($scope.order); // Tried without parseInt also
console.log($scope.storeorder) returns the right value, but it doesn't set the right value in the browser DOM.
If you don't want to use ng-options(which is the right way) , you can try with
ng-selected : Working Demo : http://jsfiddle.net/nf2m0rr1/
Example :
<body ng-app ng-controller="OrderCtrl">
<div>Order is: {{storeorder}}</div>
<select ng-model="storeorder">
<option ng-selected="{{order.value == storeorder}}" ng-repeat="order in orders" value="{{order.value}}">{{order.displayName}}</option>
</select>
</body>
function OrderCtrl($scope) {
$scope.storeorder = 2;
$scope.orders = [{
value: '1',
displayName: 'Order One'
}, {
value: '2',
displayName: 'Order Two'
}]
}
Use ng-options:
<select ng-model="storeorder" ng-init="storeorder = 0" ng-change="storeOrderChange(storeorder)" ng-options="obj.id as obj.name for obj in orders">
ng-options solved 50% of the problem but I still needed to handle the default value in the DOM and change the ng-init option. This was really bugging me. Here's the complete solution which enabled me to not set anything from the controller:
<select ng-model="storeorder" ng-options="orderdata.id as orderdata.name for orderdata in orders" ng-init="storeorder = order == 0 ? 0 : order" ng-if="orders.length > 0" ng-change="storeOrderChange(storeorder)">
<option value="">-- All orders --</option>
</select>

AngularJS null value for select

I couldn't find an elegant way for setting null values with a <select> using AngularJS.
HTML :
<select ng-model="obj.selected">
<option value=null>Unknown</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
{{obj}}
JS :
$scope.obj ={"selected":null};
When the page is loaded, the first option is selected, which is good, and the output is {"selected":null}. When that first option is reselected after having switch to another one, the output becomes {"selected":"null"} (with the quotes), which is not what I would expect.
Running example :
http://plnkr.co/edit/WuJrBBGuHGqbKq6yL4La
I know that the markup <option value=null> is not correct. I also tried with <option value=""> but it corresponds to an empty String and not to null : the first option is therefore not selected and another option which disappears after the first selection is selected by default.
Any idea ?
This should work for you:
Controller:
function MyCntrl($scope) {
$scope.obj ={"selected":null};
$scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}]
}
Template:
<div ng-controller="MyCntrl">
<select ng-model="obj.selected"
ng-options="value.id as value.value for value in objects">
<option value="">Unknown</option>
</select>
<br/>
{{obj}}
</div>
Working plnkr
You should use ng-options with select.
You can use the ngOptions directive on the select. According to the documentation:
Optionally, a single hard-coded <option> element, with the value set to an empty string, can be nested into the <select> element. This element will then represent the null or "not selected" option. See example below for demonstration.
<select ng-model="obj.selected" ng-options="key as label for (key, label) in ['No', 'Yes']">
<option value="">Unknown</option>
</select>
It's obviously a better idea to define the options list directly in the controller.
Try using ng-options instead of manually creating tags, as in this example, lightly-edited from the Angular docs:
http://plnkr.co/edit/DVXwlFR6MfcfYPNHScO5?p=preview
The operative parts here are lines 17, defining a 'colors' object, and the ng-options attributes iterating over those colors to create options.
If you REALLY want to use null, see below. You need to use ng-options and let Angular handle the mapping:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color selector</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.8/angular.min.js"></script>
</head>
<body ng-app="">
<script>
function MyCntrl($scope) {
$scope.obj ={"selected":null};
$scope.objStates = [{key:"Unknown", value:null}, {key:"Yes", value:1}, {key:"No", value:0}]
$scope.$watch('obj.selected', function(newVal){
console.log(newVal);
})
}
</script>
<div ng-controller="MyCntrl">
<select ng-model="obj.selected" ng-options="state.value as state.key for state in objStates">
</select>
<br/>
{{obj}}
</div>
</body>
</html>
I ran into the same Problem but could not solve it via 'ng-options'. My solution is:
module.directive('modelToNull', [function () {
return {
scope: {
check: "&modelToNull"
},
require: 'ngModel',
link: function ($scope, element, attrs, ngModelController) {
ngModelController.$parsers.push(function (value) {
return value == null || $scope.check({value: value}) ? null : value;
});
}
};
}]);
You can use it like this:
<select ng-model="obj.selected" model-to-null="value == 'null'">
<option value="null">Unknown</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
Can you try to use parseInt on the value? For example, both "1" and "0" will equal their respective integer values. If you run the empty string through parseInt you can easily get NaN.
> parseInt("") = NaN
> parseInt("0") === 0
> parseInt("1") === 1
Without the possibility of using ng-options I present another fix.
I've been battling this a couple of months now, using solutions presented on this question and I don't know how nobody posted this:
<option value="null"></option>
This should work on Angular 1.6 and above for sure when you are using ng-repeat for options instead of ng-options.
It's not ideal but since we are used to work on legacy code this simple fix could save your day.
the only way you can achieve that is by using a onchange event and restoring the object as initialized any other attempt to set the selected to null will remove the property from the object.
$scope.setValue=function(val){
if($scope.obj.selected=="null")
$scope.obj ={"selected":null};
}
<select ng-change="setValue()" ng-model="obj.selected">
<option value=null ng-click="obj.selected=null">Unknown</option>
<option value="1">Yes</option>
<option value="0">No</option>
</select>
this is a bad idea, you should always have values in your model instead of playing around with null and undefined
This is much easier on Angular2/Angular where you can just use
<option [value]="null">Unknown</option>
This value is no longer a string, but a real null value.

AngularJS select default value with ng-model and ng-repeat instead ng-option

I have the following code:
<select ng-model="model.RemediationCredentials" name="remediationCredential" id="remediationCredential">
<option value="0">---</option>
<option ng:repeat="cred in credentialsList"
data-index="{{$index}}" value="{{cred.Value}}">{{cred.Key}}</option>
</select>
and credentialsList looks like:
credentialsList = [ { Key: "Panda", Value: "Zoo: } ]
I think I need to use ng-repeat vs ng-option to do some basic things like the no selection and do the data-index. However, when I try to set the model it doesn't work...
$scope.model.RemediationCredentials = "Zoo"
Any suggestions?
use the Angular Select Directive:
http://docs.angularjs.org/api/ng.directive:select
Should look something more like this:
<select ng-model="model.RemediationCredentials" name="remediationCredential" id="remediationCredential" ng-options="cred.value as cred.key for cred in credentialsList">
<option value="0">---</option>
</select>

Categories

Resources