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

时间:2014-12-24 20:30:58

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

1 个答案:

答案 0 :(得分:2)

我相信你是从父控制器异步设置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
    };
  });
相关问题