다음과 같이 Bootstrap의 마크 업을 사용하는 양식이 있습니다.
<form class="form-horizontal">
<fieldset>
<legend>Legend text</legend>
<div class="control-group">
<label class="control-label" for="nameInput">Name</label>
<div class="controls">
<input type="text" class="input-xlarge" id="nameInput">
<p class="help-block">Supporting help text</p>
</div>
</div>
</fieldset>
</form>
다음과 같이 새로운 지시문 (form-input)으로 줄이고 싶은 많은 상용구 코드가 있습니다.
<form-input label="Name" form-id="nameInput"></form-input>
생성 :
<div class="control-group">
<label class="control-label" for="nameInput">Name</label>
<div class="controls">
<input type="text" class="input-xlarge" id="nameInput">
</div>
</div>
저는 간단한 템플릿을 통해이 정도 작업을합니다.
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {
label: 'bind',
formId: 'bind'
},
template: '<div class="control-group">' +
'<label class="control-label" for="{{formId}}">{{label}}</label>' +
'<div class="controls">' +
'<input type="text" class="input-xlarge" id="{{formId}}" name="{{formId}}">' +
'</div>' +
'</div>'
}
})
그러나 더 많은 고급 기능을 추가해야 할 때가 있습니다.
템플릿에서 기본값을 지원하려면 어떻게해야합니까?
내 지시문의 선택적 속성으로 “type”매개 변수를 노출하고 싶습니다. 예 :
<form-input label="Password" form-id="password" type="password"/></form-input>
<form-input label="Email address" form-id="emailAddress" type="email" /></form-input>
그러나 아무것도 지정하지 않으면 기본값으로 "text"
. 어떻게 지원할 수 있습니까?
속성 유무에 따라 템플릿을 사용자 정의하려면 어떻게해야합니까?
“필수”속성이있는 경우 지원할 수 있기를 바랍니다. 예 :
<form-input label="Email address" form-id="emailAddress" type="email" required/></form-input>
경우 required
지시문에 존재하는, 내가 생성에 추가하고 싶습니다 <input />
출력에, 그렇지 않으면 그것을 무시합니다. 이것을 달성하는 방법을 잘 모르겠습니다.
이러한 요구 사항이 단순한 템플릿을 넘어서서 사전 컴파일 단계를 사용해야한다고 생각하지만 어디에서 시작해야할지 모르겠습니다.
답변
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.replaceWith(htmlText);
}
};
})
답변
Misko가 제안한 솔루션을 사용하려고했지만 제 상황에서는 템플릿 html에 병합해야하는 일부 속성 자체가 지시어였습니다.
불행히도 결과 템플릿에서 참조하는 모든 지시문이 제대로 작동하지는 않았습니다. 각도 코드를 살펴보고 근본 원인을 찾을 충분한 시간이 없었지만 잠재적으로 도움이 될 수있는 해결 방법을 찾았습니다.
해결책은 템플릿 html을 만드는 코드를 컴파일에서 템플릿 함수로 옮기는 것이 었습니다. 위의 코드를 기반으로 한 예 :
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
template: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
return htmlText;
}
compile: function(element, attrs)
{
//do whatever else is necessary
}
}
})
답변
위의 답변은 안타깝게도 제대로 작동하지 않습니다. 특히 컴파일 단계에는 범위에 대한 액세스 권한이 없으므로 동적 속성을 기반으로 필드를 사용자 정의 할 수 없습니다. 연결 단계를 사용하면 (비동기 적으로 DOM을 만드는 등의 측면에서) 가장 큰 유연성을 제공하는 것 같습니다. 아래 접근 방식은 다음과 같은 문제를 해결합니다.
<!-- Usage: -->
<form>
<form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
return {
restrict: 'E',
compile: function(element, attrs) {
var fieldGetter = $parse(attrs.field);
return function (scope, element, attrs) {
var template, field, id;
field = fieldGetter(scope);
template = '..your dom structure here...'
element.replaceWith($compile(template)(scope));
}
}
}
})
답변
내가 사용한 결과는 다음과 같습니다.
저는 AngularJS를 처음 접했기 때문에 더 나은 / 대체 솔루션을보고 싶습니다.
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
scope: {},
link: function(scope, element, attrs)
{
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.html(htmlText);
}
}
})
사용 예 :
<form-input label="Application Name" form-id="appName" required/></form-input>
<form-input type="email" label="Email address" form-id="emailAddress" required/></form-input>
<form-input type="password" label="Password" form-id="password" /></form-input>
답변
