Javascript AngularJS:如何从同一个指令控制器访问指令范围?
HTMLJavascript AngularJS:如何从同一个指令控制器访问指令范围?,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,HTML <authorname skim="skim"></authorname> 指令 .directive('authorname', function() { return { restrict: 'E', scope: { skim: '=skim' }, controller: function($scope, User) { // console.log('sk
<authorname skim="skim"></authorname>
指令
.directive('authorname', function() {
return {
restrict: 'E',
scope: {
skim: '=skim'
},
controller: function($scope, User) {
// console.log('skim.author: ', skim.author); doesn't work
// console.log('$scope.skim.author: ', $scope.skim.author); doesn't work
// console.log('$scope.skim: ', $scope.skim); undefined
User.get({ _id: skim.author }, function(user) {
$scope.author = user.name;
});
},
template: '<small>Skim by {{author}}</small>' // but can access {{skim.author}} here
};
});
.directive('authorname',function(){
返回{
限制:'E',
范围:{
撇渣:'=撇渣'
},
控制器:功能($scope,User){
//console.log('skim.author:',skim.author.);不工作
//console.log(“$scope.skim.author:”,$scope.skim.author);不工作
//console.log(“$scope.skim:”,$scope.skim);未定义
get({u id:skim.author},函数(User){
$scope.author=user.name;
});
},
模板:{{author}}浏览//但可以在此处访问{{Skim.author}}
};
});
我可以访问模板中的
skim.author
,但不能访问控制器(我需要它)。如何在控制器中访问它?我相信您正在从父控制器异步设置skim对象,可能是从另一个ajax调用。但您的指令可能已经实例化(首先运行/实例化控制器,然后运行链接函数)。因此,当您尝试访问$scope.skim
时,它还不存在。模板中的绑定之所以有效,是因为它们在从父控制器向skim
赋值后的摘要循环中由angular更新。因此,一种方法是创建一个临时观察者,直到填充了skim
two-way-bound值
.directive('authorname', function() {
return {
restrict: 'E',
scope: {
skim: '=skim'
},
controller: function($scope, User) {
/*Create a temporary watch till you get skim or
watch skim.author according to how you are assigning*/
var unWatch = $scope.$watch('skim', function(val){
if(angular.isDefined(val)) { //Once you get skim
unWatch(); //De-register the watcher
init(); //Initialize
}
});
function init(){
User.get({ _id: skim.author }, function(user) {
$scope.author = user.name;
});
}
},
template: '<small>Skim by {{author}}</small>' // but can access {{skim.author}} here
};
});
.directive('authorname',function(){
返回{
限制:'E',
范围:{
撇渣:'=撇渣'
},
控制器:功能($scope,User){
/*创建一个临时手表,直到你得到skim或
根据分配的方式观看skim.author*/
var unWatch=$scope.$watch('skim',函数(val){
如果(angular.isDefined(val)){//一旦你得到skim
unWatch();//取消注册观察者
init();//初始化
}
});
函数init(){
get({u id:skim.author},函数(User){
$scope.author=user.name;
});
}
},
模板:{{author}}浏览//但可以在此处访问{{Skim.author}}
};
});
$scope.skim.author
您就是这样做的skim
在scope上公开。您可以通过$scope.skim
访问它。阅读本文了解更多信息:哦,好的。如果人们在评论中回答问题而不是作为官方答案,这是否意味着我应该删除该问题?如果你删除该问题,我不会删除该问题,除非确实有必要,例如,标记、投票否决以遗忘等。即使有人在评论中回答,您可以用这些注释回答您自己的问题,这样就有了一个可接受的、有效的答案。您是对的,skim
是由于ajax调用而在父控制器中异步设置的。你的解释和解决方案都很完美。谢谢