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

相關問題