我使用AngularJS 1.5,我想创建一个指令,使我的表单更容易。
我做了一个简单的指示:
app.directive('fieldDirective', function($http, $compile) {
var getTemplateUrl = function(field) {
var type = field.type;
var templateUrl = '/assets/views/fields/';
return templateUrl += type + '.html';
}
var linker = function(scope, element) {
var templateUrl = getTemplateUrl(scope.field);
$http.get(templateUrl).then(function(data) {
element.html(data.data);
$compile(element.contents())(scope);
});
}
return {
template: '<div ng-bind="field"></div>',
restrict: 'E',
scope: {
field: '=field',
ngModel: "=model"
},
link: linker
};
我为一个字段制作了一个HTML模板:
<div class="form-group">
<label class="control-label">
{{ label }}
<span class="symbol required" ng-show="field.required"></span>
</label>
<input type="text" ng-model="ngModel" ng-required="field.required" class="form-control">
</div>
我在这样的视图中测试过:
<field-directive field="field" model="testForm"></field-directive>
<field-directive field="field" model="field.model"></field-directive>
{{ testForm }}
当我使用&#34; testForm&#34;时, testForm 值被绑定。在模型中,但不与field.model。这是我的领域:
$scope.field = {
"label" : "documents.TITRE",
"type" : "textfield",
"model": "testForm",
"required" : true
};
我可以将模型名称设为动态吗?