I am refactoring some angularjs with a new directive and I am trying to access a controllers scope from the directive. Here is the directive:
(function () {
/**
* Config
*/
var moduleName = 'eBayPartsFinder.directives.categoryFilters';
/**
* Module
*/
angular.module(moduleName, []).directive('categoryFilters', categoryFiltersDirective);
function categoryFiltersDirective() {
return {
restrict: 'E',
scope: {
model: '=',
disabled: '=',
onChange: '&'
},
templateUrl: BASE_URL + '/lib/EbayPartsFinder/CategoryFilters.html',
link: categoryFiltersLinkFn
};
function categoryFiltersLinkFn($scope, element, attrs, ctrl, transclude) {
$scope.Init = function () {
var category = sessionStorage.getItem(`EbayPartsFinder.BatchResults.Category.${$scope.Batch.Id}`);
var subCategory = sessionStorage.getItem(`EbayPartsFinder.BatchResults.SubCategory.${$scope.Batch.Id}`);
if (category) {
$scope.FiltersStaging.BatchFilters.CategoryId = category;
}
if (subCategory) {
$scope.FiltersStaging.BatchFilters.SubCategoryId = subCategory;
}
}
$scope.Init();
}
}
})();
In my controller I have
searchResultsController = function ($scope, $http, $timeout, shoppingCart) {
$scope.Init = function () {
$scope.Filters = {
BatchFilters: {
ManufacturerId: null,
BrandId: null,
CategoryId: null,
SubCategoryId: null
},
GlobalFilters: {}
};
$scope.FiltersStaging = angular.copy($scope.Filters);
$scope.CategoryOptions = [{ Id: null, Description: "" }].concat($scope.Categories);
$scope.SubCategoryOptions = [];
}
}
I need access to $scope.Categories or $scope.CategoryOptions in the directive. Is there a way I can access/modify it in the directive?
You have two choices to use a Controller in a directive.
` return { restrict: 'E',
`
return { restrict: 'E',
The function contollerFn() is to be defined in the same way as the function categoryFiltersLinkFn().