Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular, in directive, adding to the template an element with ng model

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.

like image 227
Delremm Avatar asked Mar 26 '13 08:03

Delremm


2 Answers

Try

var a_input = angular.element($compile('<input type="text" ng-model="animals[0][' + i + '].name"/>')($scope))
elem_0.append(a_input);
like image 135
Arun P Johny Avatar answered Nov 27 '22 12:11

Arun P Johny


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/

like image 23
charlietfl Avatar answered Nov 27 '22 13:11

charlietfl