AngularJS: 自定义指令中的 ngView

AngularJS: ngView inside a custom directive

我正在尝试在自定义指令中使用 ng-view,但它不起作用,也没有给我任何控制台错误。

这是我的指令:

(function() {
    'use strict';

    angular
        .module('app')
        .directive('header', Header);

    Header.$inject = ['USER_AGENT'];

    function Header(USER_AGENT) {
        return {
            restrict: 'A',
            templateUrl: 'app/shared/header/header.html',
            controller: controller
        }

        function controller($scope) {
            $scope.isMobile = USER_AGENT.isMobile;
        }
    }

})();

header.html 文件中,我调用了 ng-view 就像我在外部调用它一样(当它工作时)。 是否可以将 ngView 嵌套在自定义指令中?

AngularJS 不支持在一个应用中使用多个 ng-view。如果你想要它 - 你必须使用另一个路由引擎,例如 Angular UI 的 ui-router

即使你可以使用它,你也不应该使用它,因为这不是 Angular 的正确方法 directive 应该被视为 web 组件 inputselect

请记住,您的 header.html 只是一个视图,几乎可以被任何东西使用,只是视图

.directive('myDirective', function($timeout) {
  return {
    restrict: 'A',
    templateUrl: 'app/shared/header/header.html',
    controller: controller
});

或(使用ui-router

$stateProvider
  .state('home', {
    url: '/?accountkey',
    templateUrl: 'app/shared/header/header.html',
    controller: controller
});