AngularJS Input Value Don't Update When Erasing The Text - javascript

<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names" multiple>
</select>
<input value="{{selectedName[0]}}">
</div>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
As you can see I have a select that should update the input value when clicking on an option, and it works, but when I erase some text from the input and click on an option it won't update the input value anymore.
Note: when i check the html in the inspector the value attribute is updated but not visually in the input element
Is there any explanation or solution to this?Thanks.

I would recommend to not use $scope object in your project but just to quick resolve your issue. There is plenty way to achieve it for example you can use ng-change directive. Instead of value attribute use ng-model directive. As I see select has multiply attribute use join() inside ng-change fn to change array to a string with multiply values.
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-change="update(selectedName)" ng-model="selectedName"
ng-options="x for x in names" multiple>
</select>
<input ng-model="selected">
</div>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
$scope.update = function(value) {
$scope.selected = value.join();
};
});

You can use same ng-model on the input element to maintain bidirectional communication between the select and input elements.
However since you use multiple directive on the select element, the selected model value is saved as an array, while the value entered manually in the input is saved as a string.
You can overcome this issue by adding a directive to the input element that parses the model value to an array, here is the example:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names" multiple></select>
<input ng-model="selectedName" to-array>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
app.directive('toArray', function(){
return{
require: 'ngModel',
link: function(scope, elem, attrs, ctrl) {
function toArray(viewValue){
return viewValue && viewValue.split(',');
}
ctrl.$parsers.unshift(toArray);
}
};
});
</script>

probably you are trying to select the same range of items starting from THE SAME value. In your example you try to show exclusively first selected item.
change:
<input value="{{selectedName[0]}}">
into:
<input value="{{selectedName}}">
seems to be working fine. For this example I would recommend using: ui-select

Related

AngularJS changing dropdown value with ng-model

nameList contains [“Julia”, “Evan”, “Tomas”];
select ng-model=“names” ng-options=“x for x in nameList”
In controller, I have a service api call GetNameByID/{id}”and depending on the id, I want to initialize the dropdown value of the modal form.
So if the user clicks ID 1, the dropdown defaults to Julia.
The problem is within the service call, when I try to initialize the model by doing $scope.names = data, it adds an empty option at the top instead of selecting Julia. When I console.log(data), it prints “Julia” but it becomes <option value=“?”></option>
How can i fix this?
So Lets have a HTML example for this case:
<div ng-app ng-controller="MyCtrl">
<select ng-model="names" ng-options="item for item in nameList">
</select>
<p>Selected : {{names}}</p>
<button ng-click="Update(2)"> Update(1)</button>
</div>
and Conrtoller has one service call which update your dropdown accordingly based on index.
function MyCtrl($scope) {
$scope.names = "Julia"
$scope.nameList = ["Julia", "Evan", "Tomas"];
$scope.Update = function(_value){
$scope.names = $scope.nameList[ parseInt(_value)] ;
}
}
Please have a look into running code, jsfiddle.
You can just use ng-init to initialize the dropdown first value like so:
<select ng-model="names" ng-init="names = data[0]" ng-options="x for x in data">
<option value="">Select</option>
</select>
Where [0] in data[0] is the position of the array.
Here is an example where you can set the option
In html file
<select ng-model="selectedName" ng-options="x for x in nameList"></select>
In js file
app.controller('myCtrl', function($scope) {
var id = 1;
$scope.names = ["Julia", "Evan", "Tomas"];
$scope.selectedName = $scope.names[id-1]; <---- here you can pass you id.
});
subtract id with 1 because array start with 0. Hope this is what you want to acheive.

ng-repeat with options doesn't return object as value

I have a loop "ng-repeat" inside of
<select ng-model="something"></select>
so that each option in a list is rendered as an
<option>
inside of select block. My aim is to make "something" (which is a ng-model attached to select) to be equal to a selected object inside of the list. At this moment when I do "value="{{option}}" as a parameter of option, I have a JSON object as a String. But what I need is to get an object as an object. The code looks like this:
<select ng-model="something">
<option ng-repeat="option in list" value="{{option}}">{{option.name}}</option>
</select>
The thing I want is easily done by using ng-options, but I need to add additional "style" parameters depending on option.anotherField to each
<option>
You can use ng-value instead of value, which gives you the object you want:
<select ng-model="something">
<option ng-repeat="option in list" ng-value="option">{{option.name}}</option>
</select>
What about approach via temp proxy and it's relation with something variable with the help of ng-change($scope.setModel) directive:
(function(angular) {
'use strict';
angular.module('app', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [{name:'Tom',age:23},{name:'Max',age:33},{name:'Sam',age:43}];
$scope.something = $scope.list[0];
$scope.temp = $scope.something.name;
$scope.setModel = function(){
for(var item of $scope.list)
if(item.name == $scope.temp){
$scope.something = item;
break;
}
}
}]);
})(window.angular);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller="ExampleController">
<select ng-change='setModel()' ng-model='temp'>
<option ng-repeat='option in list track by option.name' ng-attr-title='{{option.age}}'>{{option.name}}</option>
</select>
<div>something: {{something | json}}</div>
</div>

how to pass a varible from an option from to my Controller?

Can someone show me how to gather the value select on.change of the dropdown box and then use that value as a varible in my controller.
for some reason the $ColorPicked varible will not revolve in the $scope.base = response.data.type.$ColorPicked; BUT if i just remove the $ColorPicked and type in Red it works no problem.
I am still very new to Angular and JS for that matter so please excuse my stupidity. I have Googled and Googled for a clear cut answer and I got nothing.
INDEX.HTML
<h3>Color:</h3>
<select class="formBoxes" id="ColorPicked">
<option value="Red">Redd</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>
SCRIPT.JS
$ColorPicked = "Red";
var app = angular.module("computer",['ngRoute'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/main',{
templateUrl: 'archetype.html',
controller:'MainCtrl'
}).
otherwise({redirectTo:'/main'})
}])
.controller('MainCtrl', ['$scope', '$http', function($scope, $http){
$http.get('archetype.json').then(function(response){
$scope.base = response.data.type.$ColorPicked;
;
});
}]);
you need to use ng-model to bind the selected value to the controller's property. If you want to initialize the select input to a value on the model, then you need to use ng-options
<select ng-model="selectedColor"
ng-options="opt.value as opt.label for opt in opts">
</select>
and in your controller you would have the following on your scope:
$scope.opts = [
{ value:'red', label:'Red' },
{ value:'blue', label:'Blue' },
{ value:'green', label:'Green' },
]
$http.get(...).then( function( response ){
$scope.selectedColor = response.data.type.$colorPicked;
})
There are two things,
(i)You need to have a $scope variable defined for the ColorPicked inorder to provide the default selection.
(ii)You need to have ng-model which gets bind to the variable. Pass the selected Color to the function using the ng-change directive
HTML:
<select ng-model="ColorPicked" ng-change="setItem(ColorPicked)">
<option>Red</option>
<option>Blue</option>
<option>Green</option>
</select>
Controller:
function MyCtrl($scope) {
$scope.ColorPicked = "Red";
$scope.setItem = function(opt) {
$scope.base =opt;
}
}
DEMO
Working Demo for your requirement

how can access selected option value in function by AngularJs

I want function get access selected option value by angularJs but not when select tag change or trigger event .
I Use this code when option change.
<select name='type' class='form-control' data-ng-model='type' data-ng-change='change(type)'>
<option value='asc' selected>asc</option>
<option value='desc'>desc</option>
</select>
var app = angular.module('app', []);
app.controller('ctrl', function($scope){
alert($scope.type);
});
Unless you set the default value all you get is null when you do something like console.log($scope.type); but the proper way is to initialize your model with the default value like $scope.type='asc'; first in your controller then you can access the default value whenever you want.
UPDATE: take a look at this Plunker
There are many ways of doing what you have asked. To start with if you want to set the default selected item then set it from the controller as I have done in the example below. So that later when you bind the select to something else then it will be rather simple for you ie. you won't have to change any code.
var app = angular.module('app', []);
app.controller('ctrl', function($scope){
$scope.type = 'asc';
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="ctrl">
<select name='type' class='form-control' data-ng-model='type'>
<option value='asc'>asc</option>
<option value='desc'>desc</option>
</select>
<p>My Selected type: {{type}}</p>
</body>

Unable to update value of Select from AngularJs

I am unable to update value of select from AngularJs.
Here is my code
<select ng-model="family.grade" >
<option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option>
</select>
Here are the options which i am using to populate my select
var options = [{text:'Pre-K',id:'Pre-K'},
{text:'K',id:'K'},
{text:'1',id:'1'},
{text:'2',id:'2'},
{text:'3',id:'3'},
{text:'4',id:'4'},
{text:'5',id:'5'},
{text:'6',id:'6'},
{text:'7',id:'7'},
{text:'8',id:'8'},
{text:'+',id:'+'}];
Here is mu js code.
$scope.$watch("family_member.date_of_birth" ,function(newValue, oldValue){
$scope.family.grade = "1"
})
When ever value of family_member.date_of_birth changes it should set they value of select to 1. But this change is not visible on UI.
You should use ngSelected to select the option.
it could be something like this:
<select ng-model="family.grade" >
<option ng-repeat="option in options"
value='{{option.id}}' ng-selected="family.grade==option.id">
{{option.text}}</option>
</select>
Hope this helps.
I think you are looking for the track by clause of ng-options:
<option ng-repeat="option in options track by option.id">{{option.text}}</option>
However, you will still need to supply an object with an id property to set:
$scope.$watch("family_member.date_of_birth" ,function(newValue, oldValue){
$scope.family.grade = { id: "1" }
})
The options array indiviual elements are objects. So the respective ng-model also need to be an object. So even when it is being changed in js, the respective object has to be provided rather than a string.
Sample demo: http://plnkr.co/edit/naYcnID29SPa90co0leB?p=preview
HTML:
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.options = [{text:'Pre-K',id:'Pre-K'},
{text:'K',id:'K'},
{text:'1',id:'1'},
{text:'2',id:'2'},
{text:'3',id:'3'},
{text:'4',id:'4'},
{text:'5',id:'5'},
{text:'6',id:'6'},
{text:'7',id:'7'},
{text:'8',id:'8'},
{text:'+',id:'+'}];
$scope.family = {};
$scope.family_member = {
date_of_birth: '10-Jan-1986'
};
$scope.$watch("family_member.date_of_birth", function(newValue, oldValue) {
$scope.family.grade = $scope.options[2];
});
});

Categories