2013-03-26 75 views
9

我试图在ng指令中添加ng模型的输入元素。角度,在指令中,添加到ng模型元素

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

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

回答

12

尝试

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

谢谢,工作正常。 – Delremm 2013-03-26 10:00:37

+1

http://jsfiddle.net/N2TDT/1/小提琴 – Delremm 2013-03-26 10:00:57

5

您正在指令超过必要的复杂超过阵列手动循环时,你可以在指令模板使用嵌套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/