Just looking for an initial steer on my AngularJS implementation.
Background
Started work on a clients new site which uses a popular CMS as the backend and AngularJS has been chosen as the client side framework.
Functionality
Build a simple control that will manage alerts generated from the CMS.
If the alert has been accepted already, remove the alert.
If not, leave there and attach to the 'alertToggle' to save the cookie when it's clicked and remove the html.
Note
To keep a clean separation between backend and front-end I am avoiding logic in the HTML like ng-click="toggle" and instead using my custom alertToggle directive to achieve this. Same thing with not using ng-class for toggling alert--active.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
angular.module('alert', ['ngCookies'])
.controller('alertController', function ($scope, $cookieStore) {
$scope.is_active = true;
$scope.cookie_key = null;
$scope.cookie_expiry = new Date(new Date().setYear(new Date().getFullYear() + 2));
$scope.initalizeFromCookie = function () {
if ($scope.cookie_key !== null &&
$cookieStore.get($scope.cookie_key)) {
$scope.is_active = false;
}
};
$scope.toggle = function (override) {
var is_active = typeof override === 'boolean' ? override : !$scope.is_active;
if (!is_active) {
$scope.saveCookie();
}
return ($scope.is_active = is_active);
};
$scope.saveCookie = function () {
if ($scope.cookie_key !== null) {
$cookieStore.put($scope.cookie_key, true, { expires: $scope.cookie_expiry });
}
};
})
.directive('alert', function () {
return {
scope: true,
controller: 'alertController',
restrict: 'A',
link: function ($scope, $element, attrs) {
if ('id' in attrs && $scope.cookie_key === null) {
$scope.cookie_key = 'synergy.alert.' + attrs.id;
$scope.initalizeFromCookie();
}
if ($element.hasClass('alert--active')) {
$scope.toggle(true);
}
$scope.$watch('is_active', function (is_active) {
$element.toggleClass('alert--active', is_active);
});
}
};
})
.directive('cookieAlert', function () {
return {
scope: true,
controller: 'alertController',
restrict: 'A',
link: function ($scope, $element, attrs) {
$scope.cookie_key = 'synergy.alert.cookie-usage';
$scope.initalizeFromCookie();
}
};
})
.directive('alertToggle', function () {
return {
restrict: 'A',
link: function ($scope, $element, attrs) {
$element.on('click touchend', function (e) {
e.preventDefault();
$scope.$apply(function () {
$scope.toggle();
});
});
}
};
});