问题
I am facing is an issue which is demonstrated in the following example:
http://jsfiddle.net/nanmark/xM92P/
<div ng-controller="DemoCtrl">
Hello, {{name}}!
<div my-wrapper-directive>
<div my-nested-directive nested-data="nameForNestedDirective"></div>
</div>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('DemoCtrl',['$scope', function($scope){
$scope.name = 'nadia';
$scope.nameForNestedDirective = 'eirini';
}])
.directive('myWrapperDirective', function(){
return {
restrict: 'A',
scope: {},
transclude: true,
template: "<div ng-if='isEnabled'>Hello, <div ng-transclude></div></div>",
link: function(scope, element){
scope.isEnabled = true;
}
}
})
.directive('myNestedDirective', function(){
return {
restrict: 'A',
scope: {
nestedData: '='
},
template: '<div>{{nestedData}}</div>',
};
});
I want to create a directive (myWrapperDirective) which will wrap many other directives such as 'myNestedDirective of my example. 'myWrapperDirective' should decide if its content will be displayed or not according to ng-if expression's value, but if contents is a directive like 'myNestedDirective' with an isolated scope then scope variable 'nestedData' of 'myNestedDirective' is undefined.
回答1:
The problem is with the double-nested isolated scopes. You see, you are using the nameForNestedDirective variable, defined in the outer scope from the inner scope which is isolated. This means it does not inherit this variable, thus undefined is passed to the nested directive.
A diagram to explain:
Outer scope - DemoCtrl
- Defines: name
- Defines: nameForNestedDirective
+ Uses: name
Inner isolated scope 1 - myWrapperDirective
- Defines: (nothing)
- Inherits: (NOTHING! - It is isolated)
+ Uses: (nothing)
* Passes nestedData=nameForNestedDirective to nested directive, but
nameForNestedDirective is undefined here!
Inner isolated scope 2 - myNestedDirective
- Defines: nestedData (from scope definition)
- Inherits: (NOTHING! - It is isolated)
+ Uses nestedData
You can convince yourself this is the case by commenting out the scope definition of the wrapper directive ("hello eirini" is displayed as expected):
.directive('myWrapperDirective', function(){
return {
...
//scope: {},
...
I am not sure if the wrapper directive really needs to have an isolated scope. If it doesn't, maybe removing the isolated scope will solve your problem. Otherwise you will have either to:
- Pass the data first to the wrapper and then to the nested directives
- Pass the data to the wrapper directive, write a controller for it that exposes the data and then
requirethe wrapper controller from the nested directive.
来源:https://stackoverflow.com/questions/22296084/directives-isolated-scope-variables-are-undefined-if-it-is-wrapped-in-a-directi