Last active
August 29, 2015 14:06
-
-
Save gabrielmiller/b29423113e6a5064a2b0 to your computer and use it in GitHub Desktop.
Directive nesting and scope issues
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* There are two directives and two routes. On route 1 the child directive is used directly in the | |
* view. | |
* On route 2 the child directive is used inside of the parent directive which is used directly in the | |
* view. | |
* In route 1, the controller for the view has a variable that is bidirectionally bound into the child | |
* controller. | |
* When the page variable is manipulated from the view's controller as well as inside the child | |
* directive, the changes are updated in both controller and directive controller. | |
* In route 2, the link function of the parent directive has a variable that is bidirectionally bound | |
* into the child controller. | |
* When the page variable is manipulated from within the child directive, the changes are seen in the | |
* child directive, but not the parent directive. | |
*/ | |
// Route1 | |
// Child directive is implemented directly in the view for route1 | |
// Controller | |
$scope.currentPage = "page1"; | |
// View | |
<child-directive page-variable="currentPage"></child-directive> | |
// Route2 | |
// Parent directive is implemented in the view for route2 | |
// Child directive is implemented inside the template of parent directive | |
// View | |
<parent-directive></parent-directive> | |
// Parent Directive Link Function | |
return { | |
link: function(scope, element, attributes){ | |
scope.currentPage = "page1"; | |
changePageFromParent = function(page){ | |
scope.currentPage = ( page == "page2" ? "page2" : "page1" ); | |
} | |
scope.changePageFromParent = changePageFromParent; | |
}, | |
restrict: "E" | |
}; | |
// Parent Directive Template | |
<child-directive page-variable="currentPage"></child-directive> | |
// Child Directive | |
return { | |
controller: function($scope){ | |
changePageFromParent = function(page){ | |
$scope.currentPage = ( page == "page2" ? "page2" : "page1" ); | |
} | |
$scope.changePageFromChild = changePageFromChild; | |
}, | |
restrict: "E", | |
scope: { | |
currentPage: "=pageVariable" | |
} | |
}; | |
// Child Directive Template | |
<div ng-show="currentPage === 'page1'"> | |
I'm on page 1! | |
</div> | |
<div ng-show="currentPage === 'page2'"> | |
I'm on page 2! | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment