gpt4 book ai didi

javascript - Angular : How do you access a directives scope from the same directives controller?

转载 作者:行者123 更新时间:2023-11-30 17:07:41 27 4
gpt4 key购买 nike

HTML

<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
};
});

我可以在模板中访问 skim.author,但不能在 Controller 中访问(这是我需要的地方)。如何在 Controller 中访问它?

最佳答案

我相信您正在从父 Controller 异步设置脱脂对象,可能来自另一个 ajax 调用。但是你的指令已经实例化了( Controller 首先运行/实例化,然后是链接函数)。因此,当您尝试访问 $scope.skim 时,它还不存在。模板中的绑定(bind)是有效的,因为它们在摘要循环期间由 Angular 更新,发生在从父 Controller 将值分配给 skim 之后。因此,您可以做的一种方法是创建一个临时观察者,直到您获得 skim 填充的双向绑定(bind)值。

.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
};
});

关于javascript - Angular : How do you access a directives scope from the same directives controller?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27641908/

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