9

I'm trying to add an input element with ng-model inside a directive.

my code

the link function of my directive:

link: function (scope, element, attrs) {
        var elem_0 = angular.element(element.children()[0]);
        for (var i in scope.animals[0]) {
            elem_0.append(angular.element('<span>' + scope.animals[0][i].id + '</span>'));

            //this part doesn't work
            var a_input = angular.element('<input type="text">');
            a_input.attr('ng-model', 'animals[0][' + i + '].name');
            //end
            elem_0.append(a_input);
        }

it seems i need to call $compile() at the end, but have no idea how.

2 Answers 2

12

Try

var a_input = angular.element($compile('<input type="text" ng-model="animals[0][' + i + '].name"/>')($scope))
elem_0.append(a_input);
Sign up to request clarification or add additional context in comments.

Comments

5

You are making directive more complicated than necessary by manually looping over arrays when you could use nested ng-repeat in the directive template and let angular do the array loops:

angular.module("myApp", [])
    .directive("myDirective", function () {
    return {
        restrict: 'EA',       
        replace: true,
        scope: {
            animals: '=animals'
        },
        template: '<div ng-repeat="group in animals">'+
                       '<span ng-repeat="animal in group">{{animal.id}}'+
                             '<input type="text" ng-model="animal.name"/>'+
                        '</span><hr>'+
                   '</div>'

    }
});

DEMO: http://jsfiddle.net/Ajsy7/2/

Comments

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.