角,在指令,从而增加了与模板纳克模型中的元素(angular, in directive, addi

2019-08-18 01:03发布

我试图用一个指令内NG-模型添加输入元素。

我的代码

我的指令的链接功能:

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

看来我需要调用$编译()结尾,但不知道怎么样。

Answer 1:

尝试

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


Answer 2:

你被列上手动循环时,你可以使用嵌套使得指令超过必要的复杂ng-repeat的指令模板,让角度做了数组循环:

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/



文章来源: angular, in directive, adding to the template an element with ng model