![](/img/trans.png)
[英]Why can't the $rootScope be accessed in the html call to the directive?
[英]Why directive is avaible in $rootScope?
它現在不是問題,但它讓我有點好奇。
我有一個簡單的指令,我不知道為什么 - 可以在$ rootScope內部使用。
JAVASCRIPT:
(function(){
var app = angular.module('myApp', ['m.directives']);
app.run(function($rootScope){
console.log($rootScope);
});
angular.module('m.directives', [])
.directive('mUserSidebar', mUserSidebarDirective);
function mUserSidebarDirective() {
return {
restrict: 'A',
replace: true,
template: "<p>{{userSidebar.date | date : 'HH:mm'}}</p>",
controller: mUserSidebarController,
controllerAs: 'userSidebar'
};
};
mUserSidebarController.$inject = ['$interval'];
function mUserSidebarController($interval) {
var vm = this;
vm.date = new Date();
vm.logOut = function(){
console.log('log out');
}
function refreshDate(){
$interval(function(){
vm.date = new Date();
}, 1000);
}
refreshDate();
}
})();
HTML:
<div data-ng-app="myApp">
<p style="font-weight: bold"> directive: </p>
<div data-m-user-sidebar></div>
<p style="font-weight: bold; margin-top: 50px">rootScope</p>
<div>{{$root.userSidebar}}</div>
</div>
示例: http : //jsfiddle.net/y8qgmhcw/
更有趣的是,如果我將它與ui-router一起使用並且我放置了指令:
1) ui-view內部 :$ rootScope中沒有該指令
2) 外部ui-view :它可以在$ rootScope中使用
所以。 問題是:
1)為什么會這樣?
2)這是我的錯嗎? 我錯過了什么嗎? :-)
3)我可以做任何事情來省略這種行為嗎?
弄清楚了!
由於我的指令定義對象“scope”變量未定,我的指令使用其父作用域($ rootScope)。
所以, DDO應該是這樣的:
function mUserSidebarDirective() {
return {
restrict: 'A',
replace: true,
scope: true,
template: "<p>{{userSidebar.date | date : 'HH:mm'}}</p>",
controller: mUserSidebarController,
controllerAs: 'userSidebar'
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.