AngularJS: selecting option from dropdown menu - angularjs

Here is my code:
<select class="form-control" name="author" ng-options="author as author.fullname for author in authors" ng-model="author" ng-required="true"></select>
How would I change selected value from controller?

Simply set the $scope.author to whatever author you want, for example:
$scope.author = $scope.authors[2];
Here is an example jsBin
Or look up the author some how (by name, id?) and set the $scope.author or whatever to that value.

Angular works on "2-way binding". ng-model="author" binds your dropdown to $scope.author so a change in either the dropdown or the controller will reflect on both places, hence the binding.
So from your ng-options I'm assuming you have an array called authors of type author so in your controller simply
$scope.author = $scope.authors[0];
Remember that in the controller you need the $scope. before the variable and in the html ng-model or other ng directives you do not need the $scope. prefix

Related

Incompatibility between ng-value and ng-model [duplicate]

As far as i understood ng-model sets the value for that particular element in which the model is been assigned.
given that how is ng-value different from ng-model?
It works in conjunction with ng-model; for radios and selects, it is the value that is set to the ng-model when that item is selected. Use it as an alternative to the 'value' attribute of the element, which will always store a string value to the associated ng-model.
In the context of radio buttons, it allows you to use non-string values. For instance, if you have the radio buttons 'Yes' and 'No' (or equivalent) with values 'true' and 'false' - if you use 'value', the values stored into your ng-model will become strings. If you use 'ng-value', they will remain booleans.
In the context of a select element, however, note that the ng-value will still always be treated as a string. To set non-string values for a select, use ngOptions.
Simple Description
ng-model
Is used for two way binding of variable that can be available on scope as well as on html.
which has $modelValue(value reside in actual scope) & $viewValue (value displayed on view).
If you mentioned on form with name attribute then angular internally creates validation attributes for it like $error, $valid, $invalid etc.
Eg.
<input type="text/checkbox/radio/number/tel/email/url" ng-model="test"/>
ng-value
Is used to assign value to respective ng-model value like input,
select & textarea(same can be done by using ng-init)
ng-value does provide good binding if your are setting ng-model value through ajax while writing value attribute doesn't support it
Basically meant to use for radio & option tag while creating select options dynamically.
It can only have string value it, it doesn't support object value.
HTML
<input
[ng-value="string"]>
...
</input>
OR
<select ng-model="selected">
<option ng-value="option.value" ng-repeat="option in options">
{{option.name}}
</option>
</select>
...
A good use for ng-value in input fields is if you want to bind to a variable, but based on another variable's value. Example:
<h1>The code is {{model.code}}.</h1>
<p>Set the new code: <input type="text" ng-bind="model.code" /></p>
When the user types in the input, the value in the title will be updated. If you don't want this, you can modify to:
<input type="text" ng-value="model.code" ng-bind="model.theNewCode" />
theNewCode will be updated, but code will remain untouched.
According to the https://docs.angularjs.org/api/ng/directive/ngValue, ngValue takes an "angular expression, whose value will be bound to the value attribute of the input element".
So, when you use ng-value="hard", it is interpreted as an expression and the value is bound to $scope.hard (which is probably undefined).
ngValue is useful for evaluating expressions - it has no advantage over value for setting hard-coded values. Yet, if you want to hard-code a value with ngValue, you must enclose it in '':
ng-value="'hard'"
ng-model is intended to be put inside of form elements and has two-way data binding ($scope --> view and view --> $scope) e.g. <input ng-model="val"/>.
or you can say The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
The documentation clearly states that ng-value should not be used when doing two-way binding with ng-model.
From the Docs:
ngValue
Binds the given expression to the value of the element.
It can also be used to achieve one-way binding of a given expression to an input element such as an input[text] or a textarea, when that element does not use ngModel.
— AngularJS ng-value Directive API Reference
Instead, initialize the value from the controller:

scope variable becomes blank after assigned to ng-model in select list

Hi I have a angular controller like as below
adm.controller('mainController', ['$scope', function($scope){
$scope.selectedItem = '13';
}]);
And I have a cshtml file which hold a kendo drop down and this have following line.
<div>
{{selectedItem}}
<select id="ddlParameter" k-options="datasourceName" ng-model="selectedItem" data-role="dropdownlist" />
</div>
Now dropdown is successfully bind with elements of datasource. when I see output of this html file, nothing selected in dropdown and even expression (enclosed in {{}} brackets) also not displayed any value.
Now I remove ng-model from dropdown, expression (enclosed in {{}} brackets) getting resolve and its display 13 on browser.
please tell what is the problem and how this is inter-related..
You must provide further information to pinpoint the problem. All your source in a plunker would be a good move.
But from what you've provided I can guess if your data for the select provides integers as option values you must feed an integer to $scope.selectedItem for it to preselect an option.
Also why don't you use the native ng-options directive?
something like:
<select id="ddlParameter" ng-options="row.value as row.name for (key, row) in datasourceName track by key" ng-model="selectedItem" data-role="dropdownlist" />

Can i use ng-model with <p> tag?

I am new to angular-js and i think this is a basic question how to get the value from a paragraph tag in angular-js? I tried with using ng-model but doesn't giving the value.Can anyone help me?
ng-model is working for two way binding. p tag is not supported for ng-model. if you want to bind p tag then you can use ng-bind or {{}}.
<p ng-bind="test"></p>
plunker code here with ng-bind
No. You can not use ng-model for <p> tag. If you want to show the value of scope variable inside <p> tag, Then you can use expressions.
Example
<p> {{ variable }} </p>
This will show the value of variable into paragraph.
Ng-model is not supported for P,H tags,,,
if you want to bind tags then use ng-class
<p ng-class="localUser.yourdata">{{localUser.yourdata}}</p>
<h1 ng-class="localUser.yourdata">{{localUser.yourdata}}</h1>
hope this is help full
You can only directly mutate that ng-model in the controller to which the view is binded via an input tag. You could use {{}} or ng-bind for one way binding, from controller to view. But to achieve two way data binding you need an input tag or other alternatives like select.
In your case if you want to read changes inside other tags like p tags you need to watch those tags inside the scope, using $scope.$watch and listen for updates have a callback function execute on change.
So basically you can't achieve what your trying to do here. This is because p tags have static values and they do not change, so one way data binding is the best option here, from controller to view during the initialization of that tag. No point, later, would you be able to change the value inside the p tag, thus no need for two data binding here. Thus ng-model is not supported. Only ng-bind or {{}}.

Dynamic Select List Default Selected Item - Angular JS

I have the code listed below which works fine, however when i attempt to add ng-model and related ng-change to the select, an empty option is added. I understanding why, it is because on init the selectedOption for ng-model is empty.
What I want to do is set a default value so when I can use ng-change to set options IsSelected value to true when user selects it. I'm just not sure how to go about this, I have no issues doing this when I'm working with a static generated select list, but for some reason I can't figure it out for this dynamic generated list.
Any input is appreciated!
<div ng-repeat="optionType in productDetailModel.OptionTypes">
<select name="{{optionType.OptionTypeName}}">
<option ng-repeat="option in optionType.Options"
value="{{option.OptionValue}}">{{option.OptionValue}}
</option>
</select>
</div>
Here's plunkr I mocked to give a basic idea of what I have in mind: http://plnkr.co/edit/xBDfc0XzDwsF0mBiFZOv?p=preview
The initial option is blank because the model is initially undefined.
As tymeJV said, initializing your scope inside of your .js will define a default value that will be shown as selected initially.
$scope.modelName = $scope.optionType.Options[0];
It might be helpful to use ng-options instead of ng-repeat. One reason why it might be beneficial is that ng-options does not create a child scope (unlike ng-repeat). This could help simplify linking to your model and avoid confusion.
<select name="{{optionType.OptionTypeName}}" ng-model="modelName" ng-options="option for option in optionType.Options">
</select>
This article covers the basics of ng-options as well as discusses why it would be used as opposed to ng-repeat.
Hope this helps.
Use ng-options when using a select!
<select name="{{optionType.OptionTypeName}}" ng-model="someModel" ng-options="option as option for option in optionType.Options>
</select>
And then set the ngModel to the default option you want selected:
$scope.someModel = $scope.optionType.Options[0]
There is one directive of select element is ng-init but it call once while first time rendering, but if you change the options dynamically then it will not call again. So for that you need to set the model field with value in scope just below of your new option population logic.
$scope.modelName = $scope.Options[0]; // if array
$scope.modelName = $scope.Options[key]; // if Json Object

How to get the NgModelController for input fields inside a ngRepeat directive?

Normally, with a form and input fields, the form controller is published into the related scope under the form name attribute. And, the NgModelController is published under the input name attribute.
So for an input field with an ngModel directive, the NgModelController for the input field can be retrieved like $scope.myFormName.myInputFieldName
The question is how to do the same thing (get the NgModelController) for input fields inside the ngRepeat directive?
I would like to name the input fields using $index as part of the name so each template instance is uniquely named. This renders OK, so
<input name="foo_{{$index}}" ...
renders the instance with $index == 3 to
<input name="foo_3" ...
But trying to get the ngModelController via the published names does not work (it's undefined), e.g.:
$scope.myFormName.foo_3
A plunker showing this is here: http://plnkr.co/edit/jYDhZfgC3Ud0fXUuP7To?p=preview
It shows successfully getting the ngModelController for a 'plain' input element and calling $setValidity, and also shows failing to get the ngModelController for an input element inside an ngRepeat directive.
Copied the relevant section of code from the plunker below:
<div ng-repeat="element in elements">
<div ng-class="{error: form['foo_{{$index}}'].$invalid}">
<input name="foo_{{$index}}" ng-model="element.a" type="number">
<span ng-show="form['foo_{{$index}}'].$error.bar">ngRepeat bar invalid</span>
</div>
</div>
{{form.foo_0.$setValidity('bar', false)}}
#Flek is correct that the new child scopes that ng-repeat creates are the root of the problem here. Since browsers do not allow nesting of <form> elements, ngForm must be used when nesting forms, or when you want to do form validation inside ngRepeat.
See Pawel's answer on the google group thread, which shows how to use ng-form to create inner forms, and/or #blesh's SO answer.
If i understand your question correctly, you are trying to have access to the form elements created inside the ng-repeat.
Please have a look at this fiddle http://jsfiddle.net/EF5Jp/. Inside the button click handler you will have the access to the element with id myForm.foo_2. You can notice that the element is retrieved by myForm.foo_2 and not $scope.myForm.foo_2. Second thing is, changing the value using its scope and not using its value property like angular.element(element).scope().foo = 6;.

Resources