【发布时间】:2016-09-04 20:59:11
【问题描述】:
我是 Angular 的新手,并试图找到将模板动态添加/附加到页面的最佳方法。我将在模板中有几个不同的表单,当单击按钮时,我希望显示其中一个模板,具体取决于所选的选项。我不完全确定什么适合我的需要。我阅读了有关 transcluding 和 nginclude 的信息,但我不知道哪个(如果有的话)适合我的情况。
我尝试使用 transclude,但无法添加/显示任何内容。我使用this 作为参考,但我没有任何运气。这是我尝试过的。
<!-- index.html -->
<html ng-app = "testApp">
<some-component></some-component> <!-- this component has the button which the user clicks to display a form -->
<div added-form>Content here</div> <!-- transclusion here -->
</html>
//javascript controllers/components
app.component("testApp", {
templateUrl: '/static/angular-testapp/app/components/test-app/test-app.template.html',
controller: function ($scope, $rootScope, $transclude) {
...
}
});
app.component("someComponent", {
templateUrl: '/static/angular-testapp/app/components/some-component/some-component.template.html',
controller: function ($scope, $rootScope, $transclude) {
//button that when clicked will add the template
$scope.addForm = function(event){
console.log(event); //this shows, so I know the function is being reached
app.directive('addedForm', function() { //I also tried added-form as the name
return {
transclude: true,
template: "<div>the template</div><ng-transclude></ng-transclude>"
};
});
}
}
});
当我单击按钮时,没有任何反应。我在函数中放了一个console.log() 语句并显示它,所以我知道该按钮至少可以工作。我会很感激任何帮助。谢谢
更新
我不是 100% 确定,但我认为我的问题与范围有关。我将 addForm 函数中用于嵌入的代码移到任何控制器/组件之外(就在页面底部),并且它起作用了。虽然很高兴知道,但我仍然无法在按钮单击的函数中进行嵌入。
更新 2
我让它工作了,但没有使用 transclude。我发现了 $templateRequest 服务。这是我用的
//button that when clicked will add the template
$scope.addForm = function(event){
$templateRequest("/path/to/template.html").then(function(html){
//I added a div to the page with class content
var element = angular.element( document.querySelector( '.content' ) );
var template = angular.element(html);
element.append(template);
$compile(template)($scope);
});
}
【问题讨论】:
标签: javascript angularjs angularjs-ng-transclude