AngularJs 双向数据绑定不适用于自定义指令输入元素

AngularJs two-way-data-binding not working for custome directive input elements

本文关键字:自定义 指令 输入 元素 适用于 不适用 数据绑定 AngularJs      更新时间:2023-09-26

我创建了 custome 指令,用于基于后端数据创建动态表单元素。我已经创建了指令和模板。请在下面找到我的指令,模板和json字符串

angular.module('publicApp').directive('buildInput', function() {
   return {
       require: "ngModel",
       restrict:"E",
       scope:{
        build:"=", 
      },
       templateUrl:"views/directives/buildInput.html",
   }
  });

我的模板是

<label>{{build.reg_label}} 
    <span class="color-red">*</span>
</label>
<div ng-if="build.reg_type=='text'">
 <input class="form-control" type="text" required="true" ng-model="buildData[build.id]">
</div>
<div ng-if="build.reg_type=='select'">
<select ng-options="reg_option.value as reg_option.label for reg_option in build.reg_options" ng-model="buildData[build.id]">
    <option  value="" ng-show="$first">-- {{build.reg_label}} --</option>
 </select>
</div

>

查看文件是

 <div class="form-group" ng-repeat="build in builds">
                <build-input build="build" ></build-input>
   </div>

我的 json 字符串是

[
{
    "id":"1",  
    "reg_label":"What is Your Name",
    "reg_type":"text",
},
{
    "id":"2",    
    "reg_label":"Select Gender",
    "reg_options":[
        {
            "label":"Male",
            "value":"M"
        },
        {
            "label":"Female",
            "value":"F"
        }
    ],
    "reg_type":"select",
}

]

为什么我的模态不与范围变量构建数据绑定?

你的指令只知道build变量,因为你的(隔离的)作用域是这样定义的:

 scope:{
        build:"=", 
      },

听起来您的buildData变量是在定义builds的控制器上定义的,因此您应该扩展范围以如下所示:

scope:{
            build:"=", 
            buildData:"="
          },

和你的 HTML 指令声明:

<build-input build="build" build-data="buildData" ></build-input>