Изменить моделирование в директиве

0

Я хочу создать пользовательский интерфейс с помощью настраиваемой директивы. Я делаю это как:

Директива:

module.directive('testData', function() {
return {
    templateUrl: 'template/mainTemplate.html'
};

});

Шаблон:

<form class="class">
<div ng-repeat='mainJson in mainJsonData'>
    <div class='mainJson.divClass'>
        <input type="{{mainJson.inputType}}" class="{{mainJson.inputClass}}" placeholder="{{mainJson.placeHolder}}" maxlength='{{mainJson.inputMaxLength}}' ng-model="mainJson.name"/>
    </div>
</div>

Данные JSON

[
{"divClass":"form-group","inputType":"text","inputClass":"form-control","inputNgModel":"name","inputMaxLength":"10","placeHolder":"Name"},
{"divClass":"form-group","inputType":"text","inputClass":"form-control","inputNgModel":"city","inputMaxLength":"10","placeHolder":"city"},
{"divClass":"form-group","inputType":"text","inputClass":"form-control","inputNgModel":"mobile","inputMaxLength":"10","placeHolder":"mobile"}
]

но в шаблоне ng-model работает неправильно. Он создает пользовательский интерфейс:

<input type="text" ng-model="mainJson.inputNgModel" maxlength="10" placeholder="Name" class="form-control">

Это неверно. это должно выглядеть так:

<input type="text" ng-model="name" maxlength="10" placeholder="Name" class="form-control">
  • 0
    Некоторые вопросы stackoverflow.com/questions/14115701/…
  • 0
    Я новичок в угловой. Я получаю ту же проблему с нг-клик тоже.
Теги:
angular-ngmodel
angularjs-directive

1 ответ

0
Лучший ответ

Проверьте этот рабочий план

Это то, что вам нужно:

<input ng-model="mainJson[mainJson.inputNgModel]" />

Просто привяжите ng-model к ссылке объекта на значение свойства mainJson.inputNgModel массива mainJson.

Здесь следует понимать, что если вы знаете свойство массива, к которому хотите получить доступ, вы делаете это так:

var getProperty = arr.thisPropertyIKnow;

Если вы хотите динамически получить имя свойства, сделайте следующее:

var thisPropertyIDontKnow = 'valueAtRunTime';
var getProperty = arr[thisPropertyIDontKnow];

Полный шаблон с иллюстрациями.

<form class="class">
  <p>Inside directive</p>

  <div ng-repeat='mainJson in mainJsonData'>
    <div class="{{mainJson.divClass}}">
      <input ng-model="mainJson[mainJson.inputNgModel]" type="{{mainJson.inputType}}" class="{{mainJson.inputClass}}" placeholder="{{mainJson.placeHolder}}" maxlength='{{mainJson.inputMaxLength}}' />
    </div>
    <p>value of ng-model is : {{mainJson.inputNgModel}}</p>
    <p>Dipplay the value inside the input field: {{mainJson[mainJson.inputNgModel]}}</p>
  </div>
</form>

Кроме того, внутри вашей директивы вам необходимо инициализировать массив:

app.directive('testData', function() {
  return {
    templateUrl: 'mainTemplate.html',
    controller: function($scope) {
      $scope.mainJsonData = [{
        "divClass": "form-group",
        "inputType": "text",
        "inputClass": "form-control",
        "inputNgModel": "name",
        "inputMaxLength": "10",
        "placeHolder": "Name"
      }, {
        "divClass": "form-group",
        "inputType": "text",
        "inputClass": "form-control",
        "inputNgModel": "city",
        "inputMaxLength": "10",
        "placeHolder": "city"
      }, {
        "divClass": "form-group",
        "inputType": "text",
        "inputClass": "form-control",
        "inputNgModel": "mobile",
        "inputMaxLength": "10",
        "placeHolder": "mobile"
      }];
    }
  };
});

Ещё вопросы

Сообщество Overcoder
Наверх
Меню