为什么指令在$ 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>
更有趣,如果我将用它来与UI路由器一起,我把指令:
1)内UI视图:该指令是不是在$ rootScope avaible
2)外UI视图:它在$ 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'
};
};