Default value given in ng-model is not selected in drop down - angularjs

I was trying simple select drop down in my app. Where I have set a default value in ng-model. But on load the drop down does not select the ng-model value.
Below are my codes:
HTML:
View <select ng-model="viewby" ng-change="setItemsPerPage(viewby)"><option>3</option><option>5</option><option>10</option><option>20</option><option>30</option><option>40</option><option>50</option></select> records at a time.
Js:
$scope.viewby=3
$scope.setItemsPerPage = function(num) {
console.log( num);
}
Here ng-change is working perfectly.
Here '3' should be selected on load. I tried ng-init and selected='selected' also and both are not working. Any suggestion will help.--thanks

Try like below snippet. Here default selected option was 20, you can change it to your need.
var app = angular.module('app', []);
app.controller("ctrl", function($scope) {
$scope.selectedOption = 20;
$scope.setItemsPerPage = function(num) {
console.log(num);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="ctrl">
View
<select ng-model="selectedOption" ng-change="setItemsPerPage(selectedOption)">
<option>3</option>
<option>5</option>
<option>10</option>
<option>20</option>
<option>30</option>
<option>40</option>
<option>50</option>
</select>
records at a time.
</div>
</div>

In angular, Better way is to define the options as array and bind them, so that ng-model will get updated.
JS:
$scope.model = 30;
$scope.options = [10, 20, 30,40,50];
HTML
<select ng-change="setItemsPerPage(model)" ng-model="model" ng-options="value for value in options"></select>
DEMO

Related

ng-include not displaying included table

HTML script
<div>
<select ng-model="selectView">
<option value="empTable.html">Table View</option>
<option value="empList.html">List View</option>
</select>
<div ng-include="selectView"></div>
</div>
Angular script
var angScript = angular.module("multiselectapp",[]). controller ("multicontroller", function ($scope){
var empList = [
{ name:"sue", gender:"female" },
{ name:"Joe", gender:"male" }
];
$scope.employees =empList;
$scope. selectView ="empTable.html";
});
The empTable.html and empList.html has basic HTML script using ng-repeat to display the table and list view.
The angular script file is loaded and all paths are good to go having cross verified them with a $scope.message="file detected in html“ message which is displayed on HTML page.
But the table and list is not displayed at all.
Suggestions please!
Ng-include=" '{{selectedView}}' "
if its not gonna work try removing {{}}
Try out
<div ng-include src="selectView"></div>
It seems it works for me:
https://embed.plnkr.co/wFaG4m?p=preview
<body ng-controller="MainCtrl">
<p>selected item is : {{selectedItem}}</p>
<p> name of selected item is : {{selectedItem.name}} </p>
<select ng-model="selectedItem" ng-options="item.name for item in items"></select>
<div ng-include="selectedItem.name"></div>
</body>
var app = angular.module('plunker', []);
Js:
app.controller('MainCtrl', function($scope) {
$scope.items = [];
$scope.selectedItem = { name: 'a.html'};
$scope.items = [{name: 'c.html'},{ name: 'a.html'}];
});
$scope. selectView ="empTable.html";
Here unnecessary space is there between $scope and the variable name. Try removing space as below $scope.selectView ="empTable.html";

how to use indexof in array set in angularjs

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
$scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
$scope.onChange = function() {
var a = this.drop.state; }
});
</script>
<body>
<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state"> {{x.name}} </option>
<select>
</div>
</body>
In this code, I can be able to get the selected value from the textbox in the variable a. Now, I need to get the code value of the name selected. Is it possible using indexof(). And I need it in dynamic ie., when the 'state' is selected I need that corresponding 'code' from the array set.
<option value="{{x}}" ng-repeat = "x in state"> {{x.name}} </option>
If you add the value on your Option, you may get the complete object, and accessing the code and the Value
you can assign code as value to option
<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}}
Demo
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
$scope.drop = {}
$scope.state = [{name:'TamilNadu', code:1}, {name:'Kerala', code:2}, {name:'Karnataka', code:3}];
$scope.onChange = function() {
var a = $scope.drop.state
console.log(a)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-change="onChange()">
<option ng-repeat = "x in state" ng-value="x.code"> {{x.name}} </option>
</select>
</div>
Even though the other answer is valid, this is the right way to go about it:
<select id="stat" ng-model="drop.state" ng-options="x.code as x.name for x in state" ng-change="onChange()">
<option value="">Select a value</option>
</select>
If the purpose of the ng-change was to get the state code, this way it's not needed. Your ng-model will be equal to the selected state code.
You can bind data to a single property., and can access both. with preferred ng-options .
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope) {
$scope.state = [{
name: 'TamilNadu',
code: 1
}, {
name: 'Kerala',
code: 2
}, {
name: 'Karnataka',
code: 3
}];
$scope.onChange = function() {
alert(this.drop.state.name);
alert(this.drop.state.code);
}
});
</script>
<body>
<div ng-app="myApp" ng-controller="myctrl">
State :
<select id="stat" ng-model="drop.state" ng-options= "x as x.name for x in state" ng-change="onChange()"> </select>
</div>
</body>

get ng-model in $scope variable angularjs

I have this html code:
<select class="" ng-model="livre_selection" material-select multiple watch>
<option ng-repeat="livre in livres">{{livre.titre }}</option>
</select>
can I get the "livre_selection" in the controller and put it in a variable inside the controller so that I can use it ?
Thank you
Yes, AngularJS has two way data binding. whatever you put in the ng-model will be available in the controller through $scope object.
in your case you can access it by $scope.livre_selection
yes you can get that.follow the example.check ng-change and ng-click functions.you can do it by using both or only one function.
<html>
<body ng-app="myApp" ng-controller="yourCtrl">
<select ng-model="livre_selection" ng-change="a();" material-select multiple watch>
<option ng-repeat="livre in livres">{{livre.titre }}</option>
</select>
<input type="button" value="save" ng-click="b();">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('yourCtrl', function($scope) {
$scope.livres=[{titre:"a"}];
var selectedValue;
$scope.a = function(){
selectedValue = $scope.livre_selection;
}
$scope.b = function(){
alert(selectedValue);
}
});
</script>
</body>
</html>
Try
$scope.livre_selection = '';
Because $scope is basically a map, but more advisable yould be to use upperCase variable naming, like so:
$scope.liveReSelection = '';
After it, you will be able to access this variable in your controller.
You can read more here.
Controller
$scope.livre_selection = ""; <br>
var localVariable = "";
$scope.changeValue=function(changedVal){ localVariable = changedVal; }
HTML
Write an ng-change in the html near to the controller.
<select class="" ng-change="changeValue(livre_selection)" ng-model="livre_selection" material-select multiple watch>
<option ng-repeat="livre in livres">{{livre.titre }}</option>
</select>

AngularJS, ng-repeat on radio and $scope.watch

I'm using this example: https://jsfiddle.net/qnw8ogrk/1/ to create my radio-buttons.
I would like to be able to use $scope.watch on the radio-buttons, but I'm not able to use:
$scope.watch('selected', ...
What should I assign to .watch to be able to detect whenever a user clicks on a radio button?
Actual mistake was $scope.watch should be $scope.$watch Having watcher over a scope variable would not be the good idea. Instead of placing watcher over ng-model I'd suggest you to use ng-change which will only fires up when radio button ng-model value gets changed.
<label ng-repeat="option in options">
<input type="radio" ng-change="test()" ng-model="$parent.selected" ng-value="option" />{{option}}
</label>
And then don't use get rid of $parent notation for accessing outer scope of ng-repeat you could switch to use controllerAs pattern, and then change ng-controller directive to use alias of controller. Also that will change the controller implementation, bind value to this(context) instead of $scope
Markup
<div ng-controller="mainController as vm">
<label ng-repeat="option in vm.options">
<input type="radio" ng-change="vm.test()" ng-model="vm.selected" ng-value="option" />{{option}}
</label>
</div>
Controller
appModule.controller('mainController', function($scope) {
var vm = this;
vm.selected = 'red';
vm.options = ['red', 'blue', 'yellow', 'green'];
vm.test = function() {
alert('Changed');
}
});
Forked Plunkr
I agree with #PankajParker, but it is possible from you controller as well. You just got the syntax wrong, it is $scope.$watch, not $scope.watch
Have a look at this: https://jsfiddle.net/qnw8ogrk/32/
Fiddle: https://jsfiddle.net/stevenng/qnw8ogrk/33/
Markup
<div ng-app="app">
<div ng-controller="mainController">
<label ng-repeat="option in options">
<input type="radio" ng-change="picked(this)" ng-model="$parent.selected" ng-value="option"/>{{option}}
</label>
</div>
</div>
Script
var appModule = angular.module('app', []);
appModule.controller('mainController', function($scope) {
$scope.selected = 'red';
$scope.options = ['red', 'blue', 'yellow', 'green'];
$scope.picked = function($scope) {
alert('you picked: ' + $scope.selected);
}
});

Get value when selected ng-option changes

I have in my .html page a dropdown list,
Dropdown:
<select ng-model="blisterPackTemplateSelected" data-ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates">
<option value="">Select Account</option>
</select>
I want to execute an action when the user select a value. So In my controller I did:
Controller:
$scope.$watch('blisterPackTemplateSelected', function() {
alert('changed');
console.log($scope.blisterPackTemplateSelected);
});
But the changing the value in the dropdownlist doesn't trigger the code : $scope.$watch('blisterPackTemplateSelected', function()
As a result I tried another method with a : ng_change = 'changedValue()' on the select tag
and
Function:
$scope.changedValue = function() {
console.log($scope.blisterPackTemplateSelected);
}
But the blisterPackTemplateSelected is stored into a child scope. I read that the parent can't get access to the child scope.
What is the correct/best way to execute something when a selected value in a dropdown list changes? If it's method 1, what am I doing wrong with my code?
as Artyom said you need to use ngChange and pass ngModel object as argument to your ngChange function
Example:
<div ng-app="App" >
<div ng-controller="ctrl">
<select ng-model="blisterPackTemplateSelected" ng-change="changedValue(blisterPackTemplateSelected)"
data-ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates">
<option value="">Select Account</option>
</select>
{{itemList}}
</div>
</div>
js:
function ctrl($scope) {
$scope.itemList = [];
$scope.blisterPackTemplates = [{id:1,name:"a"},{id:2,name:"b"},{id:3,name:"c"}];
$scope.changedValue = function(item) {
$scope.itemList.push(item.name);
}
}
Live example: http://jsfiddle.net/choroshin/9w5XT/4/
I may be late for this but I had somewhat the same problem.
I needed to pass both the id and the name into my model but all the orthodox solutions had me make code on the controller to handle the change.
I macgyvered my way out of it using a filter.
<select
ng-model="selected_id"
ng-options="o.id as o.name for o in options"
ng-change="selected_name=(options|filter:{id:selected_id})[0].name">
</select>
<script>
angular.module("app",[])
.controller("ctrl",['$scope',function($scope){
$scope.options = [
{id:1, name:'Starbuck'},
{id:2, name:'Appolo'},
{id:3, name:'Saul Tigh'},
{id:4, name:'Adama'}
]
}])
</script>
The "trick" is here:
ng-change="selected_name=(options|filter:{id:selected_id})[0].name"
I'm using the built-in filter to retrieve the correct name for the id
Here's a plunkr with a working demo.
Please, use for it ngChange directive.
For example:
<select ng-model="blisterPackTemplateSelected"
ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates"
ng-change="changeValue(blisterPackTemplateSelected)"/>
And pass your new model value in controller as a parameter:
ng-change="changeValue(blisterPackTemplateSelected)"
Best practise is to create an object (always use a . in ng-model)
In your controller:
var myObj: {
ngModelValue: null
};
and in your template:
<select
ng-model="myObj.ngModelValue"
ng-options="o.id as o.name for o in options">
</select>
Now you can just watch
myObj.ngModelValue
or you can use the ng-change directive like so:
<select
ng-model="myObj.ngModelValue"
ng-options="o.id as o.name for o in options"
ng-change="myChangeCallback()">
</select>
The egghead.io video "The Dot" has a really good overview, as does this very popular stack overflow question: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?
You can pass the ng-model value through the ng-change function as a parameter:
<select
ng-model="blisterPackTemplateSelected"
data-ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates"
ng-change="changedValue(blisterPackTemplateSelected)">
<option value="">Select Account</option>
</select>
It's a bit difficult to know your scenario without seeing it, but this should work.
You can do something like this
<html ng-app="App" >
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
angular.module("App",[])
.controller("ctrl",['$scope',function($scope){
$scope.changedValue = function(item){
alert(item);
}
}]);
</script>
<div >
<div ng-controller="ctrl">
<select ng-model="blisterPackTemplateSelected" ng-change="changedValue(blisterPackTemplateSelected)" >
<option value="">Select Account</option>
<option value="Add">Add</option>
</select>
</div>
</div>
</html>
instead of add option you should use data-ng-options.I have used Add option for testing purpose
I am late here but I resolved same kind of problem in this way that is simple and easy.
<select ng-model="blisterPackTemplateSelected" ng-change="selectedBlisterPack(blisterPackTemplateSelected)">
<option value="">Select Account</option>
<option ng-repeat="blisterPacks in blisterPackTemplates" value="{{blisterPacks.id}}">{{blisterPacks.name}}</option>
and the function for ng-change is as follows;
$scope.selectedBlisterPack= function (value) {
console.log($scope.blisterPackTemplateSelected);
};
You will get selected option's value and text from list/array by using filter.
editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName
<select name="statusSelect"
id="statusSelect"
class="form-control"
ng-model="editobj.Flag"
ng-options="option.Value as option.KeyName for option in EmployeeStatus"
ng-change="editobj.FlagName=(EmployeeStatus|filter:{Value:editobj.Flag})[0].KeyName">
</select>
I had the same issue and found a unique solution. This is not best practice, but it may prove simple/helpful for someone. Just use jquery on the id or class or your select tag and you then have access to both the text and the value in the change function. In my case I'm passing in option values via sails/ejs:
<select id="projectSelector" class="form-control" ng-model="ticket.project.id" ng-change="projectChange(ticket)">
<% _.each(projects, function(project) { %>
<option value="<%= project.id %>"><%= project.title %></option>
<% }) %>
</select>
Then in my Angular controller my ng-change function looks like this:
$scope.projectChange = function($scope) {
$scope.project.title=$("#projectSelector option:selected").text();
};
I have tried some solutions,but here is basic production snippet. Please, pay attention to console output during quality assurance of this snippet.
Mark Up :
<!DOCTYPE html>
<html ng-app="appUp">
<head>
<title>
Angular Select snippet
</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
</head>
<body ng-controller="upController">
<div class="container">
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-3">
<div class="form-group">
<select name="slct" id="slct" class="form-control" ng-model="selBrand" ng-change="Changer(selBrand)" ng-options="brand as brand.name for brand in stock">
<option value="">
Select Brand
</option>
</select>
</div>
<div class="form-group">
<input type="hidden" name="delimiter" value=":" ng-model="delimiter" />
<input type="hidden" name="currency" value="$" ng-model="currency" />
<span>
{{selBrand.name}}{{delimiter}}{{selBrand.price}}{{currency}}
</span>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js">
</script>
<script src="js/ui-bootstrap-tpls-2.5.0.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Code:
var c = console;
var d = document;
var app = angular.module('appUp',[]).controller('upController',function($scope){
$scope.stock = [{
name:"Adidas",
price:420
},
{
name:"Nike",
price:327
},
{
name:"Clark",
price:725
}
];//data
$scope.Changer = function(){
if($scope.selBrand){
c.log("brand:"+$scope.selBrand.name+",price:"+$scope.selBrand.price);
$scope.currency = "$";
$scope.delimiter = ":";
}
else{
$scope.currency = "";
$scope.delimiter = "";
c.clear();
}
}; // onchange handler
});
Explanation:
important point here is null check of the changed value, i.e. if value is 'undefined' or 'null' we should to handle this situation.

Resources