how to keep directive's state
by przno
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-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>
JavaScript
(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);