【问题标题】:Angular JS. set ng-model correctly on repeatable select directive角 JS。在可重复的选择指令上正确设置 ng-model
【发布时间】:2014-09-15 06:35:14
【问题描述】:

刚开始学习 AngularJS。 我编写了这个控制器和指令来重复选择表单项,因为我需要做一些服务器端工作来填充它的选项。

这是 HTML 中的指令:

<form-dropdown ng-init="getDropdown('category')" class="form-control"></form-dropdown>

这是控制器,它为每个下拉菜单和指令执行 .get 脚本:

$scope.getDropdown = function(query) {
        $http.get('assets/php/get_dropdown.php?op='+query)
        .success(function(data, status) {
                    $scope.select = data;
        });
};

myFormElementApp.directive('formDropdown', function() {
          return {
                restrict: 'E',
                scope: true,
                replace: true,
                template: '<select id="{{select.name}}" name="{{select.name}}" ng-options="template.key for template in select.items"></select>'
          };
    });

这是我从脚本中获取的用于填充选择的 JSON:

{
    "name":"category",
    "items":[
         {"key":"Choose Category","value":""},
         {"key":"Shirts","value":"shirts"},
         {"key":"Pants","value":"pants"},
         {"key":"Shoes","value":"shoes"},
         {"key":"Accessories","value":"accs"},
         {"key":"Cosmetics","value":"cosmetics"},   
         {"key":"Gift cards","value":"giftcards"}
    ]
} 

我希望 ng-model 成为 JSON 中的“名称”,但每次将其放入指令模板时都会出错。我还希望选择选项的值来自 JSON 的“值”和来自“键”的文本。我有它应该在的“键”,但值只是数组中该项目的顺序(0、1、2等),我将其中一个作为每个选择的第一个元素:

<option value="?" selected="selected"></option>

我在其他地方读到过这种情况发生的原因是因为我的模型设置不正确。我应该如何重写我的控制器或指令,以便我可以正确设置 ng-model?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-controller angularjs-ng-model


    【解决方案1】:

    我觉得应该可以

    $scope.getDropdown = function(query) {
            $http.get('assets/php/get_dropdown.php?op='+query)
            .success(function(data, status) {
                        $scope.select = data;
    $scope.dropValue = data.items[0];
            });
    };
    
    
    myFormElementApp.directive('formDropdown', function() {
              return {
                    restrict: 'E',
                    scope: true,
                    replace: true,
                    template: '<select id="{{select.name}}" name="{{select.name}}"
     ng-options="template.key for template in select.items track by template.key" ng-model="dropValue"></select>'
                  };
            });
    

    【讨论】:

    • 谢谢。它确实删除了奇怪的第一个选项,但我仍然需要正确设置值。
    • 您要将哪个属性设置为值?
    • 我希望选项具有 JSON item.value。例如:&lt;option value="{{item.value}}"&gt;{{item.key}}&lt;/option&gt; 我应该为此使用 ng-repeat 吗?可能会摆脱很多头痛。我可以在保留该函数的同时将 ng-model 设置为数据的名称而不是 dropValue 吗?
    • 我将 ng-options 切换为 template.key for template in select.items track by template.value 并且成功了!感谢您的所有帮助!
    • 如果您没有其他问题,也请支持我的回答 :) 提前谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多