Reputation: 887
I have a root component that inputs items to a child component:
angular.module('demoApp', ['listing'])
.component('smartComponent', {
templateUrl: 'smartComponent.template.html',
controller: function() {
var self = this;
self.items = [{
id: 1,
text: 'item1'
}, {
id: 2,
text: 'item2'
}];
self.selectItem = function(item) {
console.log('Selected item: ' + JSON.stringify(item));
};
}
})
There is one-way binding to the items for the child component:
angular.module('listing', [])
.component('listing', {
templateUrl: 'listing.template.html',
bindings: {
items: '<',
onSelect: '&'
}
});
I can easily handle clicks to select an item with ng-click
. But I am not sure how to handle a select
drop-down.
<div class="form-group">
<select id="test" class="form-control" ng-change="$ctrl.onSelect({item: item})" ng-model="$ctrl.itemId" ng-options="item.id as item.text for item in $ctrl.items track by item.id" required>
<option value="">---Please select---</option>
</select>
Here is a plunker with a working ng-click, and non-working select: http://plnkr.co/edit/lQAhsqvsyjwCRhvkhSuS?p=preview
How do I get to pass an item to the parent component with select
? Thanks!
Upvotes: 1
Views: 440
Reputation: 1787
I was able to get the results you were getting with the ng-click
by changing the ng-options
and ng-model
values in listing.template.html
from your plunk.
You had this:
<select id="test"
class="form-control"
ng-change="$ctrl.onSelect({item: item})"
ng-model="$ctrl.itemId"
ng-options="item.id as item.text for item in $ctrl.items track by item.id"
required>
I got it to work by changing it to this:
<select id="test"
class="form-control"
ng-change="$ctrl.onSelect({item: $ctrl.item})"
ng-model="$ctrl.item"
ng-options="item.text for item in $ctrl.items"
required>
item
isn't actually a value available on the $scope, as it could only available in the option
children. But if you use the same value for ng-model
as you do for the parameter you are passing into onSelect
, the selected value will be available to you. I know that I removed a lot of the clauses you were using in the ng-options
, but hopefully this will get you back on track.
Upvotes: 1