angular,in directive,向模板添加具有ng模型的元素

时间:2013-03-26 08:14:02

标签: angularjs angularjs-directive

我正在尝试在指令中添加带有ng-model的输入元素。

my code

我的指令的链接功能:

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);
        }

似乎我需要在最后调用$ compile(),但不知道如何。

2 个答案:

答案 0 :(得分:12)

尝试

var a_input = angular.element($compile('<input type="text" ng-model="animals[0][' + i + '].name"/>')($scope))
elem_0.append(a_input);

答案 1 :(得分:5)

当您可以在指令模板中使用嵌套ng-repeat并让angular执行数组循环时,通过手动循环数组,使指令变得比必要更复杂:

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/