4

我正在创建一个指令,通过监听$ rootScope上的$ routeChangeError事件来显示和显示内容。angular.js指令templateUrl无法绑定范围

我得到了这一切通过内联模板,像这样的工作:

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,但是当我尝试,我得到一个$编译错误:

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}}"> 

我想,也许我不得不使用范围设置,但我不明白怎么。我发现文档有点混乱。

我在正确的轨道上吗?

+0

你能提供一个小提琴? –

+0

(http://jsfiddle.net/wq35d/1/) - 我不太熟悉在jsFiddle中使角度工作,所以这个例子不运行,也许你可以修复它。另外我不确定我是否正确地广播了$ routeChangeError(在我的项目中,它在路由失败的解析后触发)。 –

+0

我已经更新了你的小提琴所以它的工作:http://jsfiddle.net/wq35d/3/看看你是否可以调整它来重现你的问题,或者它可以给你一些洞察力。 – KayakDave

回答

2

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

一般来说,templateUrl无法解释$ rootScope注入.directive

Directives.directive( '...',函数($ rootScope)

所以你不能使用$ rootScope语法。你的看法这只能可以,如果你使用模板来完成:“...”,而不是在这里看到,掌握这项技术。您的指令内,可以改为:

AngularJS evaluate $rootScope variable in directive template

比使用其他模板注入$ rootScope到您的控制器中,并在您的视图中注册一个本地的$ scope变量。看起来像你的控制器里面:

$ scope.headertype = $ rootScope.currentHeaderType;

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

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

+0

你能提供一个小提琴吗? – WebWanderer

相关问题