我有一个下拉列表,应该会在更改时导致数据提取。我不需要双向绑定到下拉模型。我只是想让它最初填充一个部门列表,当用户选择一个部门时,它会获得该部门中的用户列表。
选择如下:
<select class="form-control" id="selDepartmentList" ng-model="departmentList" ng-change="getUsersInDepartment(document.getElementById("selDepartmentList").options[document.getElementById("selDepartmentList").selectedIndex].value)">
<option value="-1">All</option>
<option ng-repeat="dept in departmentList"
value="{{dept.DepartmentId}}">
{{dept.DepartmentName}}
</option>
</select>
我在没有ng-model的情况下尝试了ng-change,但由于某些原因ng-change需要ng-model,因此失败了。我尝试将ng-model设置为null并清空字符串,但都没有工作。我也尝试过根本不使用ng-change并使用onchange,但是因为它连接到我的控制器,所以无法通过onchange找到getUsersInDepartment。将ng-model设置为departmentList后,下拉列表将不会保留值,任何选择都将被删除。
我想要发生的是,当用户选择一个部门时,它会将该部门的ID传递给getUsersInDepartment,然后获取用户列表。但是现在getUsersInDepartment从未被调用。
departmentList在我的控制器中定义并附加到$ scope。我见过的所有示例都有某种selectedModelObject,它们绑定到下拉列表。我没有其中一个。
我的控制器如下:
controller('AdminTableCtrl', function ( $scope, coreAPIservice ) {
$scope.userList = [];
$scope.departmentList = [];
coreAPIservice.GetUserList().success(function (response) {
$scope.userList = response;
});
coreAPIservice.GetDepartmentList().success(function (response) {
$scope.departmentList = response;
});
$scope.getUsersInDepartment = function(deptId) {
if(deptId === -1) {
coreAPIservice.GetUserList().success(function (response) {
$scope.userList = response;
});
}
else {
coreAPIservice.GetUsersInDepartmentList(deptId).success(function (response) {
$scope.userList = response;
});
}
}
});
编辑:
我对ng-options的原始尝试:
<select class="form-control" id="selDepartment"
ng-model="selectedDepartment"
ng-options="dept as dept.DepartmentName for dept in departmentList track by dept.DepartmentId">
<option value="">Select Team...</option>
</select>
selectedDepartment定义为:
$scope.selectedDepartment = {};
答案 0 :(得分:1)
解决方案是避免使用任何角度指令装饰<select>
元素,而是将ng-click
放在每个<option>
上。
像这样:
<select class="form-control" id="selDepartmentList">
<option value="-1" selected>All</option>
<option ng-repeat="dept in departmentList"
ng-click="getUsersInDepartment(dept.DepartmentId)"
value="{{dept.DepartmentId}}">
{{dept.DepartmentName}}
</option>
</select>
答案 1 :(得分:0)
制作自定义指令应该可以解决此问题。
angular
.module('my_module')
.directive('ngCustomChange', function($parse) {
return function(scope, element, attrs) {
var fn = $parse(attrs.ngCustomChange);
element.bind('change', function(event) {
scope.$apply(function() {
event.preventDefault();
fn(scope, {$event:event});
});
});
};
});
<select ng-custom-change="$ctrl.myFunction()">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>