I'm using Angular Formly and works very well if the model is a value of the scope, like a string:
{
key: 'name',
type: 'input'
}
The problem is that I'm using a more elaborated object to handle the model, with "controller as" syntax and the name as part of the user object:
vm.user = {name: 'john', lastname: 'doe'}
And then of course, the key would be:
{
key: 'user.name',
type: 'input'
}
(Usually the vm is taken out of the key in formly notation).
The problem is that Formly uses a bracketed notation to handle the model:
template = '<input ng-model=\"model[options.key]\">'
That when processed, spits out this output:
<input name="bd.form_input_user.name_1" type="text" ng-model="model.user.name">
Of course, the model doesn't have the user object and empty fields show.
So, my question is: How can I pass or link the appropriate object to the formly model when it's a more complex object?
Thanks in advance.
The model can be defined both at the form and the field level, so it is easy to use any property in an object graph as a form field. An example:
Markup:
<div ng-controller="MyCtrl as vm">
<formly-form model="vm.data" fields="vm.userFields">
<button type="submit" class="btn btn-default" ng-click="vm.submit(vm.user)">Submit</button>
</formly-form>
</div>
JavaScript:
angular
.module('myApp', ['formly', 'formlyBootstrap'])
.controller('MyCtrl', ['$scope', function($scope) {
var vm = this;
vm.data = {
user: {
name: 'john',
lastname: 'doe'
},
extra: 'extra'
};
vm.userFields = [
{
model: vm.data.user,
key: 'name',
type: 'input',
templateOptions: {
type: 'text',
label: 'Name',
placeholder: 'Enter name'
}
},
{
model: vm.data.user,
key: 'lastname',
type: 'input',
templateOptions: {
type: 'text',
label: 'Lastname',
placeholder: 'Enter lastname'
}
},
{
key: 'extra',
type: 'input',
templateOptions: {
type: 'text',
label: 'Extra',
placeholder: 'Enter extra'
}}
];
}]);
A fiddle: http://jsfiddle.net/masa671/c37gxg3h/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With