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

后端 未结 2 1153
慢半拍i
慢半拍i 2021-02-15 09:55

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,          


        
相关标签:
2条回答
  • 2021-02-15 10:09

    Try

    var a_input = angular.element($compile('<input type="text" ng-model="animals[0][' + i + '].name"/>')($scope))
    elem_0.append(a_input);
    
    0 讨论(0)
  • 2021-02-15 10:13

    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/

    0 讨论(0)
提交回复
热议问题