What is the right way to access scope variables from a controller defined in a directive?
Example, I want to have the click event call a function on the parent directive's controller. In the parent directive, I want the controller to have access to the "constants", FOO_VIEW, BAR_VIEW, BAM_VIEW
Would it make more sense to put those constants in the top level controller, in this case SearchCtrl (not shown)?
Directives:
.directive('usersAndApps', function() {
return {
restrict:'EA',
scope: true,
controller: function() {
this.toggleView = function(viewName){
console.log('show view ' + viewName);
}
},
link:function(scope, elem, attrs) {
scope.FOO_VIEW = 'fooView';
scope.BAR_VIEW = 'barView';
scope.BAM_VIEW = 'bamView';
}
}
}).directive('usersAndAppsNav', function() {
return {
restrict: 'AE',
require:'^?usersAndApps',
replace:true,
scope:true,
link:function(scope,elem,attrs,usersAndAppsCtrl){
scope.toggleView = function(viewName){
usersAndAppsCtrl.toggleView(viewName);
}
},
templateUrl:'partials/usersAndApps/throwmeaway'
}
});
Template:
<div>
<button class="btn btn-large btn-primary" ng-click="toggleView(FOO_VIEW)">Foo View</button>
<button class="btn btn-large btn-primary" ng-click="toggleView(BAR_VIEW)">Bar View</button>
<button class="btn btn-large btn-primary" ng-click="toggleView(BAM_VIEW)">Bam View</button>
</div>
Directive and nested (child) directive:
<div ng-controller="SearchCtrl">
<users-and-apps>
<users-and-apps-nav></users-and-apps-nav>
</users-and-apps>
</div>