How can I get the last state of a directive after it has been re-rendered (the link function was executed again)? By the state I mean some data that are set by the directive itself, not passed in via attributes.
I created a simple example here on jsFiddle. What I want to accomplish is to see the same values on tab1 when clicking to tab2 and back to tab1.
HTML
<div ng-app="myApp">
<nav ng-init=" selected = 'tab1' ">
<a href="" ng-click=" selected = 'tab1' ">tab1</a> |
<a href="" ng-click=" selected = 'tab2' ">tab2</a>
</nav>
{{selected}} is selected
<div ng-if="selected == 'tab1' ">
remember the values and go to tab2
<div my-directive></div>
<div my-directive></div>
</div>
<div ng-if="selected == 'tab2' ">
go back to tab1 and see how data changed
</div>
</div>
JS
(function() {
var myApp = angular.module('myApp', ['myDirectiveModule']);
})();
(function(angular) {
angular.module('myDirectiveModule', [])
.directive('myDirective',
function() {
return {
restrict: 'A',
scope: true,
template: 'this is directive, data is {{directiveData}}',
link: function($scope, iElm, iAttrs, controller) {
console.log('link function is executing');
$scope.directiveData = $scope.directiveData || Math.floor((Math.random() * 100) + 1);
}
};
}
);
})(angular);
Different solutions came to my mind, but none seems to work, like:
- use a
service
to store the data (in array as there can be more instances of myDirective), but how would the directive know which index of the array to ask for? - use
controller
inside directive but the problem as in previous case. Also controller would be probably lost when no directive is displayed on the page - use some parent
scope
or parentcontroller
to keep track of the data, but I can not force users to create controller everywhere where they want to use the directive, not a good solution from architecture perspective. ThemyDirective
ormyDirectiveModule
should handle all its stuff alone