【问题标题】:How to pre-populate select options custom directive using angularjs如何使用 angularjs 预填充选择选项自定义指令
【发布时间】:2015-06-29 21:42:30
【问题描述】:

我是相当新的创建指令,这个指令将在我的整个应用程序中帮助我。我基本上想创建一个预先填充选项的自包含选择元素指令。对于最终结果,我要做的就是将 ngModel 绑定到它以进行设置和检索。我的 html 标记如下所示:

<div family-drop-down 
 humans-only="true" 
 ng-model="vm.selectedFamilyMember"></div>

这是角度代码:

(function(){
'use strict';

 angular.module('app', [])
  .controller('familyController', function(){
     var self = this;

     self.title = '';
     self.selectedFamilyMember = {};

     function init(){
        self.title = 'drop down example';
     }

     init();
  })
  .directive('familyDropDown', function(){
     function helperController(){
        var self = this;

        self.family = [];

        self.init = function() {
            self.family = [
                {id: 1, firstName: 'John', lastName: 'Doe', human: true},
                {id: 2, firstName: 'Jane', lastName: 'Doe', human: true},
                {id: 3, firstName: 'Baby', lastName: 'Doe', human: true},
                {id: 4, firstName: 'Dog', lastName: 'Doe', human: false}
            ];
        };
    }

    return {
      restrict: 'AE',
      replace: true,
      required: '^ngModel',
      scope: {
        humansOnly: '@',
        ngModel: '='
      },
      controller : helperController,
      controllerAs: 'vm',
      template: [
        '<select ', 
        'id = "ddlFamily" ',
        'name = "family" ',
        'class = "form-control" ',
        'ng-options = "(fam.firstName + " " + fam.lastName + " (" + fam.id + ")") for fam in vm.family" ',
        'required ',
        'title= "select family member in drop-down-list"> ',
        '<option value="">select member</value> ',
        '</select>'
        ].join(''),
      link: function(scope, element, attrs, ctrl){
        attrs('ng-model', scope.ngModel);
        ctrl.init();
      }
     };
  });
})();

Plunker:http://plnkr.co/edit/XfLRD8pzBISvQgV1mRqd?p=preview

提前感谢您的时间和帮助。

【问题讨论】:

    标签: javascript angularjs drop-down-menu angularjs-directive


    【解决方案1】:

    ngOption 属性中的 " 转义引号不正确。正确的应该是:

    template: [
        '<select ',
            'name="family" ',
            'class="form-control" ',
            'ng-options="(fam.firstName + \' \' + fam.lastName + \' (\' + fam.id + \')\') for fam in vm.family" ',
            'required ',
            'title= "select family member in drop-down-list"> ',
            '<option value="">select member</value> ',
        '</select>'
    ].join(''),
    

    演示: http://plnkr.co/edit/RLGc9dAElD1wpLN8uPm0?p=preview

    另请注意,它是 require 而不是 required。而且由于您输入错误 - 您可以将其全部删除,在您的情况下不需要它(您正在使用范围 ngModel: '=' 绑定)。

    【讨论】:

    • 非常感谢您解决这个问题。多一双眼睛看代码总是很棒的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    相关资源
    最近更新 更多