gpt4 book ai didi

javascript - 为什么指令在 $rootScope 中可用?

转载 作者:行者123 更新时间:2023-11-29 15:31:09 25 4
gpt4 key购买 nike

现在这不是问题,但让我有点好奇。

我有一个简单的指令,它 - 我不知道为什么 - 在 $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>

EXAMPLE: http://jsfiddle.net/y8qgmhcw/


更有趣的是,如果我将它与 ui-router 一起使用并放置指令:

1) ui-view:指令在 $rootScope 中不可用

2) ui-view 之外:它在 $rootScope 中可用


所以。问题是:

1) 为什么会这样?

2) 是我的错吗?我错过了什么吗? :-)

3) 我可以做些什么来避免这种行为吗?

最佳答案

想通了!

因为在我的指令定义对象“作用域”变量是未定义的,我的指令使用它的父作用域($rootScope)。

因此,DDO 应该如下所示:

function mUserSidebarDirective() {

return {
restrict: 'A',
replace: true,
scope: true,
template: "<p>{{userSidebar.date | date : 'HH:mm'}}</p>",
controller: mUserSidebarController,
controllerAs: 'userSidebar'
};
};

FIXED: http://jsfiddle.net/y8qgmhcw/1/

关于javascript - 为什么指令在 $rootScope 中可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34764161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com