4

我正在创建一个指令,该指令将通过侦听 $rootScope 上的 $routeChangeError 事件来显示和显示内容。

我通过像这样内联模板来完成所有工作:

app.directive("alert", function ($rootScope) {
    'use strict';
    return {
        restrict: "E",
        replace: true,
        template: '<div class="alert alert-warning alert-dismissable" ng-show="isError">'
            + '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'
            + '{{ message }}'
            + '</div>',
        //templateUrl: 'views/alert.html',
        link: function (scope) {
            $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
                scope.isError = true;
                scope.message = rejection;
            });
        }
    };
});

但是用 templateUrl 替换模板(正如我在示例中注释掉的那样)不起作用。模板加载,但绑定似乎不起作用。

控制台中没有错误。

我玩过各种指令设置,但没有成功让它工作。我想也许我必须要求 ngShow,但是当我尝试时,我得到一个 $compile 错误:

Error: [$compile:ctreq] http://errors.angularjs.org/undefined/$compile/ctreq?    p0=ngShow&p1=ngShow
    at Error (<anonymous>)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:6:453
    at r (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:46:477)
    at S (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:49:341)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:55:213
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:66:72
    at C (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:91:121)
    at C (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:91:121)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:92:288
    at g.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js:100:198) <div class="alert alert-warning alert-dismissable ng-binding" ng-show="{{isError}}">

我想也许我必须使用范围设置,但我不明白如何。我发现文档有点混乱。

我在正确的轨道上吗?

4

1 回答 1

3

我假设您正在谈论具有隔离范围的指令。如果是这样,则您无权访问从父范围派生的范围变量。

通常,templateUrl 无法将 $rootScope 注入解释为 .directive

Directives.directive('...', function($rootScope)

所以你不能在你的视图中使用 $rootScope 语法。这只能在您使用 template: '...' 时完成。请参阅此处以掌握此技术:

AngularJS 在指令模板中评估 $rootScope 变量

除了在指令中使用 template: 之外,您还可以将 $rootScope 注入您的控制器并使用您要在视图中使用的值注册一个本地 $scope 变量。在您的控制器内部看起来像这样:

$scope.headertype = $rootScope.currentHeaderType;

从那里,您可以在 templateUrl 视图中使用 headertype。这种技术的缺点是您松散了反向数据绑定。如果需要反向数据绑定,则必须从“=”属性派生变量

plnkr = http://mle.mymiddleearth.com/files/2013/07/aint-nobody-got-time-for-that.png

于 2013-11-16T00:21:43.607 回答