0

I have a scope in my main controller, and then I feed in an isolate scope into my link function. Is there any way to also access the main scope from my link function? Here's a simplified version of what I'm trying to do:

Angular:

angular.module('root', [])
  .controller('index', ['$scope', function($scope){
    $scope.messages = ["Hello", "Howdy", "What's up"]
  }

  .directive('myDirective', function() {
     return {
       restrict: 'E',
       scope: { greeting: '=' },
       link: function(scope, element, attrs) {
            var greeting = scope.greeting;  //one message from the array, fed in by <my-directive greeting='message'> from index.html
            var length = scope.messages.length; //length of whole messages array

            //do stuff
        }
      }
    }

HTML: (index.html)

   <body ng-app='root' ng-controller='index'>
    <div ng-repeat='message in messages'>
      <my-directive greeting='message'></my-directive> 
    </div>
</body> 

I want to be able to access both the message and the "meta" information about the entire messages array from my link function. However, right now I can only access the message (var greeting) but the length variable does not evaluate. Is there a way to do this in angular?

Let me know if you need any other clarifications!

1 Answer 1

1

The rules on isolate scopes are really simple, but hard to understand from the Angular docs.

If you omit the scope: property from the directive declaration, the directive will share scope with its parent. In other words, it will have direct access to the scope of the controller that called it, and all of its variables.

A better practice is to pass the necessary variables into the isolate scope, which you're already doing with the greetings variable. Your scope might look like this.

scope: {
  greeting: '=',
  messages: '='
}

Then write the directive like this:

<my-directive greeting='message' messages='messages'></my-directive>

And as long as $scope.message and $scope.messages are defined in your controller, you're all set.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.