【问题标题】:How to set model object as a value in AngularJS HTML select tag?如何将模型对象设置为 AngularJS HTML 选择标签中的值?
【发布时间】:2017-01-11 21:16:48
【问题描述】:

我需要在AngularJS HTML select标签中设置一个$scope的对象,我会解释清楚我的要求:

这是我的 angularjs 脚本代码:

$scope.departments = $http.get("getDepartmentList");

在部门范围内,我将从从数据库中获取的 spring mvc 控制器获取部门对象列表。

我将在 html select as 中使用的部门范围

<select name="department" 
        ng-model="department" 
        class="form-control" 
        ng-options="department as department.deptName for department in departments" 
        class="select_form" >
        option 
        value="">Select Department</option>
</select>

创建时,我可以在从选择列表中选择后获取部门对象。在修改过程中,我将有一个部门对象需要在选择列表中设置和选择,但它没有被选中,仅列出对象列表,而在修改过程中没有选择修改的对象。

在修改期间我将部门范围设置为

$scope.department = $http.get("getDepartmentById);

所以上面的代码将在范围内有一个部门对象,但它没有在列表中选择

我尝试在选择标签中使用 ng-value 作为

<select name="department" 
        ng-model="department" 
        class="form-control" 
        ng-options="department as department.deptName for department in departments" 
        ng-value="department" 
        class="select_form" >
        <option value="">Select Department</option>
</select>

但是没有用,任何人都可以帮助从 html 页面中的选择列表中设置对象。

【问题讨论】:

    标签: angularjs select angularjs-scope


    【解决方案1】:

    在 AngularJS 中,$http 是一个返回承诺的服务。它异步运行,然后您在完成处理后使用它的返回值(或异常)。

    取自docs,$http API 基于 $q 服务公开的deferred/promise API。

    您当前正在为 $scope.departments 分配一个承诺,这不是您想要的,您需要为它分配在您的 spring 控制器的响应中解析的数据。

    这里是一个如何使用 $http 服务的例子:

    // make your request to your spring mvc controller path
    $http.get("getDepartmentList").then(function(response) {
    
        // set the data from the response data object
        $scope.departments = response.data
    
    }, function(error) {
    
        // handle any errors that may occur
    
    });
    

    对于您的单个部门(我假设您可以将其设置为选中):

    // again, make your request to your spring mvc controller path 
    // but this time you should perhaps include an id parameter
    $http.get("getDepartmentById?id=").then(function(response) {
    
        // set the data from the response data object
        $scope.department = response.data
    
    }, function(error) {
    
        // again, handle any errors that may occur
    
    });
    

    【讨论】:

    • 好的,我可以理解,但我正确的列表中只有一个对象可用
    • 这取决于您从 spring mvc 控制器返回的数据。查看您的代码,如果您调用 getDepartmentList,您应该有一个对象列表。然后,您可以使用 ng-options 指令在您的选择中重复这些对象(就像您现在一样)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 2018-02-16
    相关资源
    最近更新 更多