我修正了@imaginabit 的答案:
<script type="text/ng-template" id="checkboximp.html">
<div class="checkbox">
<label>
<input type="checkbox"
class="formly-field-checkbox"
ng-model="model[options.key]">
{{to.required ? '*' : ''}}
<div ng-bind-html="to.label"> </div>
</label>
</div>
</script>
/* global angular */
(function() {
'use strict';
var app = angular.module('formlyExample', ['formly', 'formlyBootstrap', 'ngSanitize'], function config(formlyConfigProvider) {
// set templates here
formlyConfigProvider.setType({
name: 'checkboxHtml',
extends: 'checkbox',
templateUrl: 'checkboximp.html',
wrapper: ['bootstrapHasError']
});
});
app.controller('MainCtrl', function MainCtrl(formlyVersion) {
var vm = this;
// funcation assignment
vm.onSubmit = onSubmit;
// variable assignment
vm.author = { // optionally fill in your info below :-)
name: 'Kent C. Dodds',
url: 'https://twitter.com/kentcdodds' // a link to your twitter/github/blog/whatever
};
vm.exampleTitle = 'Introduction';
vm.env = {
angularVersion: angular.version.full,
formlyVersion: formlyVersion
};
vm.model = {
awesome: true
};
vm.options = {
formState: {
awesomeIsForced: false
}
};
vm.fields = [
{
key: 'awesome',
type: 'checkbox',
templateOptions: { label: 'this is a <a href="test">test</a>' }
},
{
key: 'awesome2',
type: 'checkboxHtml',
templateOptions: { label: 'this is a <a href="test">from j. lennon</a>' }
}
];
// function definition
function onSubmit() {
alert(JSON.stringify(vm.model), null, 2);
}
});
})();
http://jsbin.com/dunuyakiwe/2/edit?html,js,output
只有两个观察结果:
- 必须有 angular sanitize 库,这样才能使模板正常工作(ng-bind-html 指令)。
- 默认的复选框表单模板在组件中嵌入了标签,因此无法直接使用它,这就是创建我们自己的类型更简单的原因。