对表单输入使用可重用指令

Using a reusable directive for form inputs

本文关键字:指令 表单 输入      更新时间:2023-09-26

我刚刚通读了指令文档,但我仍然不明白如何使用可重用的代码完成以下工作。我有多个表单字段最好在select > option设置中使用,但是由于移动浏览器如何处理select s,我希望用带有模板的指令替换它(iOS放大了option s,我的一些值太长而无法在显示屏中查看)。

所以我的模板看起来像这样:

<div class="list">
    <div class="option" ng-repeat="option in form.questionOneOptions" ng-click="selectOption(option)">
        {{option}}
        <i class="checkIcon" ng-if="option.isSelected"></i>
    </div>
</div>

这将是详细信息页面上的唯一内容。它的父页面是您正在填写的字段列表,这是需要提供数据的地方。我只是不知道从哪里开始指令。每个问题都有一个孤立的范围,其中包含该问题的选项。需要有一种方法来为指令提供选项列表。所有问题都有一个包罗万象的范围,可以将记录的答案保存在一个对象中,例如form

我知道我可以使用单个控制器并复制/粘贴上述内容并使用控制器中的一个巨大对象更改form.questionOneOptions,但我试图通过将我的 DOM 操作限制为指令来以正确的方式做到这一点。

您需要使用那里的 html 作为指令的模板。然后在链接函数中实现选择选项。

app.directive('gsQuestion', function() {
    return {
        restrict: 'E',
        require: 'ngModel',
        scope: {
            ngModel: '=',
            options: '='
        },
        template:'<div class="list">'+
                   '<div class="option" ng-repeat="option in options" ng-click="selectOption(option)">'+
                    '{{option}}'+
                    '<i class="checkIcon" ng-if="option.isSelected"></i>'+
                 '</div></div>',
        link: function(scope, element, attrs) {
            scope.selectOption = function(option)
            {
                // implement selectOption
            }
        }
    };
});

然后,您可以在 html 中使用该指令。

<gs-question ng-model="myValue1" options="form.questionOneOptions"></gs-question>
<gs-question ng-model="myValue2" options="form.questionTwoOptions"></gs-question>

需要明确的是,指令可以通过使用指令的$scope变量与视图共享数据/从视图共享数据。

angular.module('app', [])
.directive('mySampleDirective', function(){
  return{
   restrict: 'AE',
   scope: {
    data: '=' // this sets up a two way binding 
   }
}, 
link: function(scope, element, attributes){
   console.log(scope.data) // <---- this is where you would do DOM manipulation, 
                           // because you have access to the element.
 }
})

然后在标记中,传入要在指令中提供的数据。

<my-sample-directive data="FeeFee"></my-sample-directive>