I am new to Angular and still learning.
Here is the sample fiddle.
I would like to know how do I convert it to a service? I find writing both setStatus on NavController
and HeaderController
seems quite wrong, are there any better way working for this one?
Scenario
When the user click on close
button, the whole nav
which with background will be displayed none while when the user clicked on menu
button, nav
will get a class of is-active
which makes the nav
displayed block.
JS
var app = angular.module('myapp', ['ngRoute']);
app.controller('NavController', function($rootScope, $scope) {
$rootScope.status = 'off';
this.setStatus = function(status) {
$rootScope.status = status;
};
});
app.controller('HeaderController', function($rootScope, $scope) {
this.setStatus = function(status) {
$rootScope.status = status;
};
});
DOM
<div ng-app="myapp">
<nav ng-controller="NavController as nav" ng-class="{ 'is-active': status == 'on' }" ng-init="nav.status" class="nav">
<div class="nav__wrapper">
<button ng-click="nav.setStatus('off')" class="nav__close">close</button>
</div>
</nav>
<header ng-controller="HeaderController as header">
<button ng-click="header.setStatus('on')">menu</button>
</header>
</div>
Any help would be greatly appreciated, thank you!