0

I'm trying to bind model data from a controller to a directive template. The directive template repeats form input types based on a form object from a controller.

The goal is to use this directive in multiple places and bind the appropriate model to the form as opposed to creating a form each time.

I've found examples using transclusion and isolated scopes, however, each of the examples I've come across seem to have the model properties hardcoded.

Here is a jsfiddle that hopefully explains better what I'm trying to achieve.

http://jsfiddle.net/N9rSa/14/

app.controller('FormCtrl',function($scope) {
    $scope.form = [
        {label:'First',type:'text',name:'first_name'},
        {label:'Last',type:'text',name:'last_name'}
    ];

    $scope.person = {first_name:'Jimmy',last_name:'Page'};
});

app.directive('formelements',function() {
    return {
        restrict: 'E',
        scope:false,
        template: '<div ng-repeat="elements in form"><input type="text" ng-model="field.name"></div>'
    }
});

Thanks for any help.

1 Answer 1

1

You can use the following as template:

template: '<div ng-repeat="element in form">' +
    '<input type="text" ng-model="person[element.name]"></div>'

Fiddle: http://jsfiddle.net/g5Mzs/

Essentially the name field is used to define the index inside the person object.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. I figured I could use form_model as my object to apply to the form everytime it's needed: jsfiddle.net/N9rSa

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.