Adam Zerner
Adam Zerner

Reputation: 19168

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

HTML

<authorname skim="skim"></authorname>

Directive

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

I can access skim.author in the template, but not in the controller (which is where I need it). How can I access it in the controller?

Upvotes: 1

Views: 46

Answers (1)

PSL
PSL

Reputation: 123739

I believe you are setting skim object asynchronously from the parent controller, possibly from another ajax call. But your directive would have instantiated already (controller runs/instantiated first and then the link function). So when you try to access $scope.skim it doesn't exist yet. Binding in the template works because they are updated by angular during a digest cycle the happened after the assignment of value to skim from the parent controller. So one way you could do is to create a temporary watcher till you get the skim two way bound value populated.

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

Upvotes: 2

Related Questions