简体   繁体   中英

AngularJS template variables not rendering when inside custom directive

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!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM