【问题标题】:Angularjs custom component vs ngSwitch directive compilation orderAngularjs 自定义组件 vs ngSwitch 指令编译顺序
【发布时间】:2017-09-02 14:52:59
【问题描述】:

有如下代码sn-p:

<my-header></my-header>
<div ng-switch="$ctrl.page">
        <div ng-switch-when="1"><component1></component1></div>
        <div ng-switch-when="2"><component2></component2></div>
        <div ng-switch-when="3"><component3></component3></div>
</div>

我希望 myHeader 组件在 ngSwitch 指令执行操作之前构建。现在 component1myHeader 之前构造。

路由表示如下代码:

$stateProvider
  .state({
    name: 'myApp',
    url: '/',
    component: 'loader',
  })
  .state({
    name: 'myApp.pages',
    url: 'pages/{id:int}',
    component: 'loader'
  });
$urlRouterProvider.otherwise('/pages/1');

【问题讨论】:

  • my-header 有什么?
  • my-header 是一个非常简单的组件,使用 HTML 模板和控制器实现 ng.IComponentOptions。没什么特别的。可能只是它注入自定义单例服务的一件事。有什么意义吗?
  • 您能否在 plunker 中重现该问题并添加问题..?

标签: javascript angularjs angularjs-ng-switch


【解决方案1】:

您可以通过在 myHeader 指令内的链接函数中公开您的控制器来实现此目的。

这样,您可以轻松地将变量添加到控制器并使用 ng-if 控制 ng-switch div 的可见性。在此处查看代码 sn-p。

啊,别忘了在包含 ng-switch 指令的 div 中添加 ng-cloak

angular
        .module('app', [])
        .controller('TestController', function($scope) {
            this.page = 1;
        })
        .directive('myHeader', function () {
            return {
                link: function (scope, element, attrs) {
                    // With element.controller() we can reach the controller that is wrapping our directive. Then, we can simply set the headerIsLoaded variable to true.
                    element.controller().headerIsLoaded = true;
                },
                scope: true,
                templateUrl: 'my-header.html'
            }
        });
<div ng-controller="TestController as ctrl">

    <my-header></my-header>

    <!-- Add a visual feedback so user knows the components are being loaded -->
    <div ng-if="!ctrl.headerIsLoaded">
        Loading...
    </div>

    <!-- If ctrl.headerIsLoaded is set to true, the ng-switch will appear -->
    <div ng-if="ctrl.headerIsLoaded"
         ng-cloak>
        <div ng-switch="ctrl.page">
            <div ng-switch-when="1">
                Page 1
            </div>
            <div ng-switch-when="2">
                Page 2
            </div>
            <div ng-switch-when="3">
                Page 3
            </div>
        </div>
    </div>

</div>

【讨论】:

  • 感谢您的回答。最后,我使用 rootScope 事件找到了解决方案。可能不是最优雅的方式,但结果已经达到。
猜你喜欢
  • 2019-11-06
  • 2015-06-21
  • 1970-01-01
  • 2014-06-24
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多