假设我有一个下拉列表,我想将onClick事件添加到列表的最后一个元素,例如:
ng-change 指令只是帮助我,如果我在下拉列表中有多个元素,否则如果我有这样的列表(只有一个元素):
我永远无法将onClick事件设置为唯一的项目,因为它永远不会更改组合框的值。
更新
<select ng-model="customer.selectedCity" ng-options="opt as opt.name for opt in customer.cityOptions"
ng-init="model="customer.selectedCity" = customer.cityOptions[0]"
ng-change="onCustomerCitySelected(customer)" ></select>
答案 0 :(得分:3)
您可以在不使用ng-change
的情况下实现此目的。请考虑以下事项:
HTML模板
<select ng-model="selectedIndex"
ng-options="index as name for (index, name) in menu">
</select>
<强>的JavaScript 强>
app.controller('SelectCtrl', function($scope) {
$scope.menu = ['London','Paris','Milan','Add new city+'];
$scope.$watch('selectedIndex', function(val) {
$scope.selectedCity = $scope.menu[val];
if (val == $scope.menu.length - 1) {
$scope.addNewCity();
$scope.selectedIndex = $scope.selectedCity = null;
}
});
$scope.addNewCity = function() {
alert('Add city from select');
};
});
您还可以考虑使用ui-bootstrap
下拉列表。
HTML模板
<div class="btn-group" dropdown>
<button type="button"
class="btn btn-primary">{{ vm.selectedCity || 'Not selected' }}
</button>
<button type="button"
class="btn btn-primary dropdown-toggle"
dropdown-toggle>
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li ng-repeat="item in vm.menu">
<a ng-if="!$last" href="#"
ng-bind="item"
ng-click="vm.selectedCity = item"></a>
<a ng-if="$last" href="#"
ng-bind="item"
ng-click="vm.addNewCity()"></a>
</li>
</ul>
</div>
<强>的JavaScript 强>
app.controller('DropdownCtrl', function() {
var vm = this;
vm.menu = ['London','Paris','Milan','Add new city+'];
vm.addNewCity = function() {
alert('Add city from dropdown');
vm.selectedCity = null;
};
});
上面的示例会产生类似这样的内容
此处所有代码的相关plunker http://plnkr.co/edit/szA1pt
答案 1 :(得分:1)
您可以尝试添加默认值,如下所示:
<select ng-model="model2" ng-options="item for item in items2" ng-change="processItemChange(model2)">
<option value="">Select Value From Items2</option>
</select>
现在您可以添加ng-change
函数来定义新值是否为add new value