how to keep directive's state
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.js"></script>
<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-show="selected == 'tab1' ">
remember the values and go to tab2
<div my-directive id=0></div>
<div my-directive id=1></div>
</div>
<div ng-show="selected == 'tab2' ">
go back to tab1 and see how data changed
</div>
</div>
JavaScript
(function() {
var myApp = angular.module('myApp', ['myDirectiveModule']);
})();
(function(angular) {
angular.module('myDirectiveModule', [])
.directive('myDirective',
function(data) {
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 = data.generateData(iAttrs.id);
}
};
}
)
.service('data', function() {
this.data = {};
this.generateData = function(id){
if (this.data[id] !== undefined)
return this.data[id]
else
return this.data[id] = Math.floor((Math.random() * 100) + 1);
};
})
})(angular);