Creating a directive can be done in various ways. Here is an example of how I structured mine:
'use strict';
myApp.directive('mySwitchOnOff', [
'$rootScope', function($rootScope) {
return {
restrict: 'C',
replace: false,
scope: { isActive: '='},
templateUrl: 'urlToTample',
link: function(scope, element, attrs) {
scope.toggleVisibility = function(section, module) {
//Do something with the scope.isActive
};
}
};
}
]);
The original directive utilizes the isActive
from the parent scope and triggers the toggleVisibility
function upon user interaction. However, I decided to optimize it by not directly binding to the parent scope. Instead, I modified the functionality to determine whether the button is active by passing the $event
to the function and checking for the active class on the target element, resulting in the following code:
'use strict';
myApp.directive('mySwitchOnOff', [
'$rootScope', function($rootScope) {
return {
restrict: 'C',
replace: false,
templateUrl: 'urlToTample',
link: function(scope, element, attrs) {
scope.toggleVisibility = function(e, section, module) {
isActive = j$(e.target).hasClass('active');
//Do something with the isActive
};
}
};
}
]);
Now the question remains: From a performance and best practices standpoint, do you believe it's more efficient to bind to the parent scope or pass the $event to the function?