javascript - 如何使用 AngularJS ng-include 之类的东西通过 id 插入 HTML

标签 javascript html angularjs

我正在使用 AngularJS 并将指令编译到我的主页中。该指令有一组按钮,这些按钮会根据指令中发生的情况而变化。 我想将按钮移动到我页面中的菜单栏之类的地方,但菜单栏不是指令的一部分。

是否可以使用 ng-include 之类的东西在菜单栏中插入按钮?

我想做的一个例子:

<body ng-app="myApp" ng-controller="Controller">
    <nav class="navbar">
        <ul class="nav nav-pills">
            <li>
                <button>A permanent button</button>
            </li>
            <div ng-include="#other-buttons></div>
        </ul>
    </nav>

    <my-directive></my-directive>

    <script type="text/javascript">
        angular.module('myApp', [])
        .controller('Controller', ['$scope', function($scope) {
          $scope.data = someData;
        }])
        .directive('myDirective', function() {
          return {
            template: '<div id="other-buttons" ng-switch="data">
                        <div ng-switch-when="this">
                            <li><button>This button</a></li>
                        </div>
                        <div data-ng-switch-when="that">
                            <li><button>That button</a></li>
                        </div>
                      </div>'
          };
        });
    </script
</body

因此,根据某些数据,指令模板会有所不同,这应该会更改导航栏中的内容。那将如何工作?

最佳答案

您可以使用 $templateCache设置和获取模板,然后通过您提供的 ID 引用它们。您可以在页面上查看示例。

myApp.run(function($templateCache) {
    $templateCache.put('buttons.html', 
                    '<div id="other-buttons" ng-switch="data">
                        <div ng-switch-when="this">
                            <li><button>This button</a></li>
                        </div>
                        <div data-ng-switch-when="that">
                            <li><button>That button</a></li>
                        </div>
                   </div>'
   );
});

然后用

加载到ng-include
<div ng-include=" 'buttons.html' "></div>

考虑到您的指令和 Controller 共享相同的范围,并且您的导航栏位于您的 Controller 内,它们应该具有相同的行为。

但是,如果您要在不共享相同范围的应用程序的不同部分使用此设置,我建议您设置一个服务来弥合两者之间的差距。

关于javascript - 如何使用 AngularJS ng-include 之类的东西通过 id 插入 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30039332/

相关文章:

javascript - 用模数循环?

jquery - 如何创建包含不同数据的 `directive` 的多个实例

javascript - 按时间顺序对带有日期的多维数组进行排序的最快方法

javascript - 单击箭头时,动画标志向左或向右移动一个位置

javascript - 无法使用异步 waterfall 运行 parse-csv 函数

html - 物化 css 轮播中的当前幻灯片

angularjs - Angular 误差: $parse:syntax Syntax Error

angularjs - 将 FireBaseAuthClient 与 AngularJS 结合使用时为 "Error: $apply already in progress"

javascript - AngularJs 如何将参数传递给 $scope.$apply?

javascript - 在 Vue 中渲染只读内容的最佳方法