【问题标题】:Adding a template/form to a page with Angularjs使用 Angularjs 向页面添加模板/表单
【发布时间】: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


    【解决方案1】:

    你可以这样试试:https://jsfiddle.net/vts1w7kt/

    只需根据模型使用 ng-hide 或 ng-show 即可显示适当的 div、表单等...

    select 以这种方式绑定到myDropDown

    <select ng-model="myDropDown">
      <option value="one">One</option>
      <option value="two">Two</option>
      <option value="three">Three</option>
    </select>
    

    然后像这样使用绑定到该模型的 ng-view 或 ng-hide:

    ng-show="myDropDown=='one'"
    

    【讨论】:

    • 谢谢,但这不是我想要的。虽然这确实有效并且我可以将它用于未来的项目,但我想弄清楚为什么 transclude 不适合我。主要原因是如果我有大型模板要添加,我不希望它们在主 html 文件中造成混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    相关资源
    最近更新 更多