我正在创建一个指令,该指令将通过在$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">×</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}}">
我想也许我必须使用范围设置,但我不明白如何。我发现文档有点混乱。
我走在正确的轨道上吗?
我假设您正在谈论具有隔离范围的指令。如果是这样,则无权访问从父作用域派生的范围变量。
通常,templateUrl 无法将$rootScope注入解释为 .directive
Directives.directive('...', function($rootScope)
因此,不能在视图中使用$rootScope语法。这只有在使用模板时才能完成:"..."相反。请参阅此处以掌握此技术:
AngularJS在指令模板中评估$rootScope变量
除了使用模板:在指令内部,您可以将$rootScope注入控制器,并使用要在视图中使用的值注册一个局部$scope变量。在控制器内部看起来像这样:
$scope.headertype = $rootScope.currentHeaderType;
从那里,您可以在模板 Url 视图中使用标头类型。此技术的缺点是会松散反向数据绑定。如果需要反向数据绑定,则必须从"="属性派生变量
波兰兹罗提 = http://mle.mymiddleearth.com/files/2013/07/aint-nobody-got-time-for-that.png