使用AngularJS的双向数据绑定在SELECT上设置默认值

时间:2015-09-23 08:32:56

标签: javascript angularjs

场景:我需要使用AngularJS在SELECT标签中显示数据列表。由于AngularJS允许双向数据绑定,我希望它能够在没有额外努力的情况下表现出来。这是我做的方法。

Model
 public class Department
    {
        public int? DepartmentId { get; set; }
        public string DepartmentName { get; set; }
    }

Query to get the data

 Departments = user.Departments.Select(x=> new Department {DepartmentId= x.UserID,DepartmentName= x.FirstName}).OrderByDescending(x=>x.DepartmentName)

将数据分配给$ scope

 $scope.loadData = function () {
                $http.get(baseurl.resolve("~/api/users/getbyid?userId=" + userId)).success(function (data) {
                    $scope.DepartmentID = data.DepartmentID;
                    $scope.profile = data;
                });
            };

SELECT中的值发生变化时的事件

   $scope.selectDepartment = function (selectedDepartment) {
        $scope.profile.DepartmentID = selectedDepartment;
    };

将数据绑定到UI

          <select data-ng-model="DepartmentID" data-ng-selected="0" data-ng-change="selectDepartment(DepartmentID)" data-ng-options="department.DepartmentId as department.DepartmentName for department in profile.Departments">

这似乎不是一个普通的方法,我需要为我设置一个$scope.profile.DepartmentID = selectedDepartment;来获取所选值。是否有正确的方法只是以另一种方式更新价值?

2 个答案:

答案 0 :(得分:0)

试试这个

$scope.selectDepartment = function (selectedDepartment) 
{
        $scope.DepartmentID = selectedDepartment;
};

从现在开始删除ng-change

<select data-ng-model="DepartmentID" data-ng-selected="0" data-ng-options="department.DepartmentId as department.DepartmentName for department in profile.Departments">

答案 1 :(得分:0)

假设您要将选定的DepartmentId从下拉列表中放入名为$ scope.profile.DepartmentID的变量。

在这种情况下,您需要为SELECT元素

添加ng-model =“profile.DepartmentID”

检查某些元素的ng-bind =“profile.DepartmentID”之类的内容。 在这里,您可以看到更新的DepartmentID。