How to select a value for option dropdown in angularJS UnitTest - angularjs

My html code is something like this and I want to select a value from dropdown and verify the same in AngularJS UnitTestCase using Jasmine
I tried using option.value but it's not working out..
<select id="company" ng-model="company" ng-change="companychange(company)" ng-options="company.ID as company.Name for company in companies"></select>
My AngularJS UnitTestCase is something like this
//somecode has been left out
$templateCache.put('selectcompany.html', directiveTemplate);
templateHtml = $templateCache.get('selectcompany.html');
formElem = angular.element('<div>' + templateHtml + '</div>');
//console.log(directiveTemplate);
$compile(formElem)($scope);
form = $scope.companyform;
companyform = form;
form2 = $compile(directiveTemplate)($scope);
$scope.$apply('companies=[{ Name: "Gold", value:0, ID: 0 },{ Name: "Silver", value:1, ID: 1 }, { Name: "Bronze", value: 2, ID: 2 }]');
}));
describe(' company ', function () {
it('selecting a dropdown ', function () {
var options = form2.find('[id="company"]')[0];
angular.element(options["value='2'"]).trigger('click');
$scope.$digest();
console.log(options.innerHTML);
expect($scope.company).toBe(2);
});
});

Related

Angularjs set checked radio not working

I have 3 radio buttons:
<label ng-repeat="mode in opMode.groupMode" class="radio-inline" title="{{mode.title}}">
<input id="rd{{mode.id}}" type="radio" class="panel-load-radio" ng-model="opdtMode.groupMode"
name="inlineRadioOptions" value="{{mode.id}}"
ng-change="changeOpdtMode(mode.id, '{{opdtMode.groupMode}}')">
{{mode.name}}
</label>
Here is Angularjs code:
$scope.opMode = { groupMode: [
{ name: "ModuleType", title: "Load processes by Module type", id: "ModuleType", isDefault: false },
{ name: "OpGroup", title: "Load processes by Operation group", id: "OpGroup", isDefault: true },
{ name: "MachineType", title: "Load processes by Machine type", id: "MachineType", isDefault: false }
]};
If isChange = true, show confirm mbox. If User click cancel, set oldValue and checked previous radio. I wrote this. However it's not working as expected:
$scope.changeOpdtMode = function (newValue, oldValue) {
if(isChange){
const msg = getMsgById(29, msgLostData);
const r = confirm(msg.value);
if (r === true) {
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
window.isChange = false;
} else {
$scope.opdtMode.groupMode = oldValue;
}
}else{
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
}
}
After 2 hours researched:
I post my answer here for everyone may see as the same issue.
<label ng-repeat="mode in opMode" class="radio-inline" title="{{mode.title}}">
<input type="radio" class="panel-load-radio" ng-value="mode.id"
ng-model="$parent.opdtMode" ng-change="changeOpdtMode(mode.id, '{{opdtMode}}')">
{{mode.name}}
</label>
Need to remove name="inlineRadioOptions" and add $parent into the model.
$scope.opdtMode = "OpGroup";
$scope.opMode = [{ name: "ModuleType", title: "Load processes by Module type", id: "ModuleType" },
{ name: "OpGroup", title: "Load processes by Operation group", id: "OpGroup" },
{ name: "MachineType", title: "Load processes by Machine type", id: "MachineType" }];
$scope.changeOpdtMode = function (newValue, oldValue) {
if(isChange){
const msg = getMsgById(29, msgLostData);
const r = confirm(msg.value);
if (r === true) {
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
window.isChange = false;
} else {
$scope.opdtMode = oldValue;
}
}else{
const lang = $scope.layoutLang.selectedLang;
loadLayout(null, lang, newValue);
}
}

unable to update the ngmodel of select list

Case :
I am trying to update the value of ng-model inside the controller but it is not working and i wonder why , any idea ?
HTML :
<select ng-model="dumm" ng-options="item.name as item.type for (name, item) in availableFilters" ng-change="selectFilter()"></select>
JS :
$scope.selectFilter = function () {
$scope.availableFilters[$scope.dumm].visible = true;
$scope.dumm = "";
};
$scope.availableFilters = {
name: {
type: 'Name',
name: 'name'
},
producttype: {
type: 'Product type',
name: 'producttype',
data: $scope.xxx
},
status: {
type: 'Status',
name: 'status',
data: $scope.unitStatusTypes
}
};
$scope.dumm should be an object rather than a string, otherwise the binding won't work - this fact is quite obscure in Angular's docs. The binding should look like this:
<select ng-model="dumm.value"...
and the variable's definition:
$scope.dumm = {value: ""};

How to edit a table row using angluarJS?

I'm searching for a solution to edit in-line table rows. Pretty much like this fiddle, but with populated comboboxes too.
function Ctrl($scope) {
$scope.model = {
contacts: [{
id: 1,
name: "Ben",
age: 28
}, {
id: 2,
name: "Sally",
age: 24
}, {
id: 3,
name: "John",
age: 32
}, {
id: 4,
name: "Jane",
age: 40
}],
selected: {}
};
// gets the template to ng-include for a table row / item
$scope.getTemplate = function (contact) {
if (contact.id === $scope.model.selected.id) return 'edit';
else return 'display';
};
$scope.editContact = function (contact) {
$scope.model.selected = angular.copy(contact);
};
$scope.saveContact = function (idx) {
console.log("Saving contact");
$scope.model.contacts[idx] = angular.copy($scope.model.selected);
$scope.reset();
};
$scope.reset = function () {
$scope.model.selected = {};
};
});
How can I make inline editable comboboxes ? Each line should have a name, age and a group of options.
It would be easier, and I would venture to say nicer, if you use ng-grid instead of html tables. The grid has built-in editing, and you can customize the kind of editor, such that your cell could display as plain text, but use a combo box for editing.
Here is a plunker that shows an editable combo box on the Gender column:
http://plnkr.co/edit/zsxqZNQCnpFySjSWcf1D?p=preview
{field:'gender', displayName: 'Gender', enableCellEdit: true,editableCellTemplate: '<span id="gender"><select ng-class="\'colt\' + col.index" + ng-input="COL_FIELD" ng-model="COL_FIELD" ng-options="c.value as c.name for c in genders"></select></span>'}]
And here is the documentation for ng-grid:
http://angular-ui.github.io/ng-grid/

AngularJS Select Not Binding To Ng-Model

My angular select isn't binding. I can tell the value is correct, but the select isn't updated. Why is not binding if the value is there?
<div ng-controller="MyController" ng-app>
<select class="form-control" ng-model="colorId"ng-options="color.id as color.name for color in colorList">
<option value="">--Select a Color--</option>
</select>
<input type="button" value="submit" ng-click="Select()"></input>
function MyController($scope) {
$scope.colorList = [{
id: '1',
name: 'red'
}, {
id: '2',
name: 'blue'
}, {
id: '3',
name: 'green'
}];
var colorId = 3;
$scope.colorId = colorId;
alert($scope.colorId);
$scope.Select = function () {
var colorId = 2;
$scope.colorId = colorId;
}
}
Here is a fiddle:
http://jsfiddle.net/ky5F4/23/
you need to change the id to a string when doing Select
$scope.Select = function () {
console.log('select fired');
var colorId = 1;
$scope.mySelection.colorId = colorId + "";
}
http://jsfiddle.net/bxkwfo0s/2/
next you should use a property of an object rather than just a scope variable, this will ensure proper model binding
ng-model="mySelection.colorId"
where the object could be something simple
$scope.mySelection = {colorId : colorId };
There are two errors with your code:
You are using colorList as your model in ng-options, but you are calling it datasets in your controller.
You use strings for the id, but set the $scope.colorId to a number.
Here is an updated fiddle changing ids to numbers and changing $scope.datasets to $scope.colorList
function MyController($scope) {
$scope.colorList = [{
id: 1,
name: 'red'
}, {
id: 2,
name: 'blue'
}, {
id: 3,
name: 'green'
}];
var colorId = 3;
$scope.colorId = colorId;
alert($scope.colorId);
$scope.Select = function () {
var colorId = 2;
$scope.colorId = colorId;
}
}
Consider making your ng-model be an object, specifically one of the objects that are already in your $scope.colorList. If you do that you should be able to avoid the post-processing you're doing in the click handler.
So your select will look like this:
<select class="form-control" ng-model="selectedColor"
ng-options="color.name for color in colorList"></select>
One gotcha is that if you have an object in your controller that looks JUST LIKE your red object, like$scope.selectedColorObj = { id : '1', name:'red' } and set the select's ng-model to that option, it won't work. Angular will see that you're setting to the ng-model to an object that's not actually in your data source and add an extra option with value="?", so I use $filter in this case to grab the matching member of the array:
$scope.colorId = '3';
$scope.selectedColor = $filter('filter')( $scope.colorList,{ id: $scope.colorId})[0];
See http://jsfiddle.net/ky5F4/92/

AngularJS matching data between json arrays and setting a selected option

$scope.opts =
{
unit: [
{ id: 1, val: "px", name: "px"},
{ id: 2, val: "%", name: "%"}
]
}
The above is my options list array and now I set my default option.
$scope.user.unit = $scope.opts.unit[0];
The above creates the following in my html
<select class="unit ng-pristine ng-valid" data-ng-options="a.name for a in opts.unit" data-ng-model="user.unit">
<option value="0" selected="selected">px</option>
<option value="1">%</option>
</select>
When I use the below I am pulling the data that was stored in a db from the options selected in the above example.
$http.get('/assets/inc/file.php?id='+thisPage).success(function(response) {
var userData = response.userData;
var locationData = response.locationData;
$scope.user = userData;
$scope.locations = locationData;
console.log($scope.user.unit);
});
This console.logs me the following Object { id=1, val="px", name="px"}
I may be wrong but the <select> box is binded to $scope.opts
How would I be able to link the retrieved data from $scope.user.unit to $scope.opts.unit so that when the data is retrieved it will then mark the correct option as :selected?
I'm not 100% sure but you can try this (or create JSFiddle):
JS:
$http.get('/assets/inc/file.php?id='+thisPage).success(function(response) {
var userData = response.userData;
var locationData = response.locationData;
$scope.user = userData;
$scope.locations = locationData;
$scope.selected = {};
angular.forEach($scope.opts.unit, function (value)
{
if (value.val == $scope.user.unit.val) {
$scope.selected = value
}
});
console.log($scope.user.unit);
});
and in View:
<select class="unit ng-pristine ng-valid" data-ng-options="a.name for a in opts.unit" data-ng-model="user.unit">
<option value="{{selected.val}}">{{selected.name}}</option>
</select>
Your ng-model for the select element is an object, and not a primitive type, which is fine, but then you reassign $scope.user to a brand new object (returned from $http.get), so user.unit is a new object too, so it's not identical to any of your ng-options. I can think of two ways which should fix the problem:
bind the select to the 'id' property of the unit object:
<select ng-options="a.id as a.name for a in opts.unit" ng-model="user.unit.id">
or leave the select bound to user.unit, but use the track by feature of ng-options:
<select ng-options="a.name for a in opts.unit track by a.id" ng-model="user.unit">
One of the things in Angular is that you rarely need to do is explicitly create <option> elements manually as the framework will generate this for you. Therefore, the following will work: (Working jsfiddle at http://jsfiddle.net/LMHLq/12/)
HTML:
<select data-ng-model='user.unit' data-ng-options="o.id as o.name for o in opts.unit"/>
JavaScript:
$scope.opts ={
unit: [
{ id: 1, val: "px", name: "px"},
{ id: 2, val: "%", name: "%"},
{ id: 3, val: "pt", name: "pt"}
]
}
$http.get('/assets/inc/file.php?id='+thisPage).success(function(response) {
var userData = response.userData;
var locationData = response.locationData;
$scope.user = userData;
$scope.locations = locationData;
console.log($scope.user.unit);
});
$scope.opts ={
unit: [
{ id: 1, val: "px", name: "px"},
{ id: 2, val: "%", name: "%"},
{ id: 3, val: "pt", name: "pt"}
]
}
I noticed that the $scope.opts builds my select element and populates it but when the data is retrieved via db it needs to go into $scope.user.unit but this is binded to $scope.opts so what I have done is sought out the ID for the item that was retrieved and then added -1 to it so it will select from the array of $scope.opts.unit
var testUnit = $scope.user.unit.id-1; //gets the ID of the unit thats been retrieved
$scope.user.unit = $scope.opts.unit[testUnit]; //sets the selected option in the dom

Resources