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

时间:2014-12-30 10:45:08

标签: javascript angularjs

我已经创建了基于后端数据创建动态表单元素的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

&GT;

查看文件是

 <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",
}

为什么我的模态没有与范围变量buildData绑定?

1 个答案:

答案 0 :(得分:0)

您的指令只知道build变量,因为您的(隔离的)范围定义如下:

 scope:{
        build:"=", 
      },

听起来您的buildData变量是在定义了builds的控制器上定义的,因此您应该将范围扩展为:

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

您的HTML指令声明:

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