【问题标题】:AngularJS ng-options, working with key value pairs in <select>AngularJS ng-options,在 <select> 中使用键值对
【发布时间】:2014-09-23 15:34:03
【问题描述】:

我一直在尝试使用通过 $http 调用检索并用于填充下拉框的对象。

我的对象如下所示:

{1: Item1
↵L", 2: "Item2
↵", 3: "Item3
↵"}

在我的控制器中:

$scope.data = {};
$http.get(baseUrl + "/Lookup/Get?param=Ref_myModel").success(function (result) {

    $scope.data.myModel = result

})
.error(function (error) {
    $scope.data.error = error;
});

终于在 HTML 中:

 <select class="form-control" id="MonStatus" ng-model="data.myModel" ng-options="key as value for (key , value) in data.myModel"></select>

选择下拉列表中填充了模型中的值,没有问题,但是一旦用户选择了一个值,该值就会被键替换。我一直在阅读试图理解 ng-options 的文档,但是我遇到了一些问题,因为所有示例都使用具有正确键、值格式的对象,而我有键和文本。

【问题讨论】:

    标签: javascript angularjs ng-options


    【解决方案1】:

    您使用 $scope.data.myModel 作为模型和选项的源元素。这些应该是分开的:

    $scope.data = {};
    $scope.data.myModel = '';
    $http.get(baseUrl + "/Lookup/Get?param=Ref_myModel").success(function (result) {
    
        $scope.data.options = result
    
    })
    .error(function (error) {
        $scope.data.error = error;
    });
    

    那么在你看来:

    <select class="form-control" id="MonStatus"
        ng-model="data.myModel" 
        ng-options="key as value for  (key , value) in data.options"></select>
    

    这会将选择绑定到 myModel 并让选项保持原样...

    一些额外的建议:

    另外,不要在控制器中调用 $http,将它们放在服务中。始终在控制器中尽可能避免逻辑,让服务/工厂负责繁重的工作。此外,将data- 放在ng-* 属性之前也是一个不错的主意。

    【讨论】:

    • 这很有效,并且在不绑定填充模型的情况下非常有意义。但是,使用的模型现在是空的。那么我们什么时候使用填充模型呢?就像这里的例子一样,mycolors 有一个值:docs.angularjs.org/api/ng/directive/select。此外,我计划将 http 调用从控制器移动到工厂,并在设置所有调用后重构以使用 routeprovider 中的 resolve 属性。
    • 如果您希望表单加载预填充,您可以预填充模型...所以在您的成功回调中(顺便说一句,另一个提示,我相信 .success.error不推荐使用.then),如果要将模型设置为预设为第二项,则可以分配$scope.data.myModel = $scope.data.options[1]
    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多