Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I'm having an issue with a custom angular directive. Basically, in the example below, the variable "name" will render correctly if outside of the scope of the directive, but not when inside the directive.

Template:

<div ng-controller="swygController">
  <div swyg="example" edit="load(id)">
    {{name}}
  </div>
  {{name}
</div>

Directive:

swyg.directive('swyg', function(){
  return {
    restrict: 'A',
    scope: {
      edit: '&'
    },
    compile: function(elm, attr){
      // Code
    },
    controller: function($scope, $element, $attrs) {
     // Code
    }
  };
});

I've tested this with the compile and controller directive functions empty (to rule out something in my directive causing the issue) and get the same result.

I'm fairly certain it's a scope issue, but can't figure out how to resolve it. It seems like I somehow need to allow the directive to inherit the controller's scope? I assumed since the directive is inside the controller, it'd be fine.

Has anyone else run into this?

Thanks for your help!

share|improve this question
up vote 0 down vote accepted
scope: { }

creates an isolated scope, meaning you can not access the parent scope and everything defined on it.

You could use $parent.name to access the parent scope name variable. But I wouldn't recommend traversing the scope using $parent.

Instead pass the name as an attribute to your directive.

I've created a plunker to demonstrate how to do this: http://plnkr.co/edit/NGNMfkgNMooq0Sul6HPH?p=preview

share|improve this answer
    
Perfect, thank you! – JKE Oct 27 '13 at 6:05

As soon as you declare scope within a directive it is then an isolated scope and therefore variables from parent scope are not the same.

There are several ways to approach:

One is using parent scope in expression. Nested scopes become nested in parent objects so you can do:

{{$parent.name}}

If nesting is 2 levels deep would be able to use $parent.$parent.name but this approach gets ugly

Or pass the variable to directive as an attribute, and include that in directive scope the same way you are doing with edit

share|improve this answer
1  
please dont encourage people to use $parent to traverse the scope. I know it's the simplest solution to the problem but it creates more problems than it solves. – bekite Oct 26 '13 at 21:44
    
@bekite not trying to encourage it and also point out it can get ugly. However, is valuable to know as a help to understanding deeper concepts within angular – charlietfl Oct 26 '13 at 21:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.