Angularjs Directive $destroy
I have an angular app setup with ng-view. In one view, in addition to the view itself, there is also a component inside that view that is dynamically loaded. This component is a di
Solution 1:
The i18n example you provided would work if you only ever used it once.
I don't think you should be doing the event binding inside the compile function. You can do it inside the link function instead:
angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
return {
restrict: 'EAC',
link: function(scope, element, attrs) {
var cleanup;
var originalText = element.text();
element.text(LocaleService.getTranslation(originalText, attrs.locale));
cleanup = $rootScope.$on('locale-changed', function(locale) {
element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
});
scope.$on('$destroy', function() {
console.log("destroy");
cleanup();
});
}
};
}]);
Alternatively, you could bind the event on the child scope itself, and use $broadcast
on the $rootScope
to trigger it. That way the event will automatically be garbage collected when the scope is destroyed:
angular.directive('i18n', ['$rootScope', 'LocaleService', function($rootScope, LocaleService) {
return {
restrict: 'EAC',
link: function(scope, element, attrs) {
var originalText = element.text();
setElText();
functionsetElText(locale){
element.text(LocaleService.getTranslation(originalText, attrs.locale || locale));
}
scope.$on('locale-changed', setElText);
}
};
}]);
$rootScope.$broadcast('locale-change', 'en-AU');
Post a Comment for "Angularjs Directive $destroy"