Implementing scope = in angular directives
I wrote a directive that looks something like this:
'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
};
}
};
}
]);
This directive uses isActive
from the parent scope. The function is toggleVisibility
triggered when the user presses the button. I thought there was no need to bind isActive
with the parent, I can find if the button isActive
by passing the $event
function and check if the target has an active class. So I rewrote the directive as follows:
'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
};
}
};
}
]);
My questions are: What do you think is best in terms of efficiency / best practice? Bind the parent scope or pass $ event to a function?
source to share
Interest Ask,
I think since you are already calling the digest loop with ng-click and not for the dom request (although hasClass has a rather poor performance level) i.e. anchoring the parent area will be faster.
Consequences of your hasClass: (from jquery source)
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 &&
(" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
The clock loop is also not cheap BUT it is anyway, so it will check the links and activate the clock action as needed, but since this is already happening I think it is faster.
But I'm just guessing here :)
source to share