我似乎无法弄清楚这一点。我需要使用 $compile(我认为)来将元素与范围连接起来。这适用于没有其他指令(特别是 ng-repeat)的元素。但不适用于具有 ng-repeat 的元素。我想出了一个例子:
Plunkr:http://plnkr.co/edit/Nmn7n631iijP1lQAZaXv?p=preview
var count = 0;
angular.module("dir", [])
.controller("main", function($scope) {
$scope.test = 1;
})
.directive('ngHello', function($compile) {
return {
scope: true,
compile: function(telem, attrs, transclude) {
var repeat = "<div>"+
"<div ng-repeat='item in items'>{{item}}</div>"+
"</div>";
var r = angular.element(repeat);
telem.after(r);
var easy = "<div>this is {{test2}}</div>";
var e = angular.element(easy);
telem.after(e);
return {
pre: function(scope, ielem, iAttrs, controller) {
$compile(r)(scope); //why doesn't this seem to work?
$compile(e)(scope);
},
post: function(scope, ielem, iAttrs, controller) {
scope.items = [];
for(var i=0; i<5; i++) {
scope.items.push(count++);
}
scope.test2 = "test4";
}
};
}
};
});
我做错了什么?
最佳答案
你不需要调用 angular.element,$compile 会获取 html。你甚至不需要使用指令的编译函数,这都可以在链接函数中完成。 $compile 返回编译后的元素。您需要将其用作要添加的元素。
来自 plunkr 的相关位:
.directive('ngHello', function($compile) {
var repeat = "<div>"+
"<div ng-repeat='item in items'>{{item}}</div>"+
"</div>";
var r = angular.element(repeat);
return {
scope: true,
link: function(scope, elem, attrs) {
scope.items = [];
scope.items.push(1);
scope.items.push(2);
scope.items.push(3);
var e = $compile(repeat)(scope);
elem.after(e);
关于javascript - AngularJS 如何使用 ng-repeat $compile 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23532261/