如何使用模型输入指令?

时间:2017-06-12 08:32:22

标签: angularjs

我有模型node

{"id":"593d408cb25f42a812000042","prefix":"array_simple",
 "title":"Array_simple","type":"3","value":["A","B","C"],"nodes":[]}

在这个obejct中,有一个字段值,其值为array:

"value":["A","B","C"]

如何使用指令显示数组中每个值的输入并在更改后将其绑定到模型?

我试着写指令:

.directive('inputArray', function ($compile) {
    return {
        restrict: 'E',
        scope: {
            data: "="
        },

        link: {
            pre: function (scope, element) {

                scope.inputs = [];

                if (angular.isArray(scope.data.value)) {
                    angular.forEach(scope.data.value, function (value) {
                        scope.inputs.push({"type": scope.data.type, "value": value});
                    });

                } else {
                    scope.inputs.push({"type": scope.data.type, "value": scope.data.value});
                }
            }
        },
        template: `<input ng-repeat="value in inputs track by $index" 
                     ng-model="node.value"
                     ng-hide="value.type=='2' || value.type=='6'" 
                     type="text" value="$$value.value$$">`,
        replace: true
    }
})

但它不会在变化后改变模型。

1 个答案:

答案 0 :(得分:0)

在尝试实现指令之前,只需使用模板和控制器:

&#13;
&#13;
  <script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app>
    <div ng-init='data = {"id":"593d408cb25f42a812000042","prefix":"array_simple",
 "title":"Array_simple","type":"3","value":["A","B","C"],"nodes":[]}'>
    </div>

    <div  ng-repeat="item in data.value track by $index">
      <input ng-model="data.value[$index]" type="text" />
    </div>

    <p>{{data}}</p>
    <p>{{data.value}}</p>
  </body>
&#13;
&#13;
&#13;

不是将数据复制到新数据模型,而是直接使用$indexproperty accessor bracket notationdata.value[$index]来使用数据模型。