AngularJS :如何从相同的指令控制器访问指令范围

AngularJS : How do you access a directives scope from the same directives controller?

本文关键字:指令控制器 访问 指令 范围 AngularJS      更新时间:2023-09-26

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,但不能在控制器中访问(这是我需要它的地方)。如何在控制器中访问它?

我相信

您正在从父控制器异步设置skim对象,可能来自另一个ajax调用。但是您的指令已经实例化了(控制器首先运行/实例化,然后是链接函数)。因此,当您尝试访问$scope.skim时,它还不存在。模板中的绑定之所以有效,是因为它们在摘要周期中按角度更新,这是在从父控制器向skim分配值之后发生的。因此,您可以做的一种方法是创建一个临时观察程序,直到填充skim双向绑定值。

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