ng-form を使用したくない場合は、フォームの name 属性を変更するカスタム ディレクティブを使用できます。このディレクティブを ng-model と同じ要素の属性として配置します。
他のディレクティブを組み合わせて使用している場合は、「ターミナル」プロパティが設定されていないことに注意してください。そうしないと、この関数を実行できません (優先度が -1 の場合)。
たとえば、このディレクティブを ng-options とともに使用する場合、次の 1 行の monkeypatch を実行する必要があります:
https://github.com/AlJohri/bower-angular/commit/eb17a967b7973eb7fc1124b024aa8b3ca540a155
angular.module('app').directive('fieldNameHack', function() {
return {
restrict: 'A',
priority: -1,
require: ['ngModel'],
// the ngModelDirective has a priority of 0.
// priority is run in reverse order for postLink functions.
link: function (scope, iElement, iAttrs, ctrls) {
var name = iElement[0].name;
name = name.replace(/\{\{\$index\}\}/g, scope.$index);
var modelCtrl = ctrls[0];
modelCtrl.$name = name;
}
};
});
ng-init を使用して $index を変数名に設定すると便利なことがよくあります。例えば:
<fieldset class='inputs' ng-repeat="question questions" ng-init="qIndex = $index">
これにより、正規表現が次のように変更されます。
name = name.replace(/\{\{qIndex\}\}/g, scope.qIndex);
複数のネストされた ng-repeat がある場合、$parent.$index の代わりにこれらの変数名を使用できるようになりました。
ディレクティブの「ターミナル」と「優先度」の定義: https://docs.angularjs.org/api/ng/service/ $compile#directive-definition-object
ng-option monkeypatch の必要性に関する Github コメント:
https://github.com/angular/angular.js/commit/9ee2cdff44e7d496774b340de816344126c457b3#commitcomment-6832095
https://twitter.com/aljohri/status/482963541520314369
アップデート:
これを ng-form で機能させることもできます。
angular.module('app').directive('formNameHack', function() {
return {
restrict: 'A',
priority: 0,
require: ['form'],
compile: function() {
return {
pre: function(scope, iElement, iAttrs, ctrls) {
var parentForm = $(iElement).parent().controller('form');
if (parentForm) {
var formCtrl = ctrls[0];
delete parentForm[formCtrl.$name];
formCtrl.$name = formCtrl.$name.replace(/\{\{\$index\}\}/g, scope.$index);
parentForm[formCtrl.$name] = formCtrl;
}
}
}
}
};
});