我正在尝试创建一个在用户单击按钮时添加大量html的指令。
angular.module('myApp').directive('testProduct', function() {
return {
restrict: 'A',
link: function(scope, elem) {
var html;
html = '<div>… a lot of html tags and contents………….';
// a lot of html tags
//I want to link to a html file like product.html
//instead of defining here.
elem.bind('click', function() {
$('.product').remove();
elem.closest('div').append(html);
})
}
};
}
);
无论如何我可以将html链接到另一个文件吗?像templateUrl:product.html
?我不能在这里使用它,因为我只想在用户点击按钮时添加这些html。
非常感谢!
答案 0 :(得分:1)
在click事件中创建一个像<div ng-include="foo.html"></div>
这样的元素并将其传递给angular.element。然后将其附加到DOM。一旦附加使用注入的$ compile服务。 $compile(dynamicIncludeElement)(scope)
。
angular.module('myApp').directive('testProduct', function($compile) {
return {
restrict: 'A',
link: function(scope, elem) {
var html = angular.element('<div ng-include="'product.html'"></div>');
elem.bind('click', function() {
var compiledHtml = $compile(html)(scope);
elem.append(compiledHtml);
})
}
};
}
);
另一种选择是自己获取HTML并编译它。
angular.module('myApp').directive('testProduct', function($http, $compile) {
return {
restrict: 'A',
link: function(scope, elem) {
elem.bind('click', function() {
$http.get('product.html')
.success(function(data) {
var compiledHtml = $compile(data)(scope);
elem.append(compiledHtml);
}
);
})
}
};
}
);