AngularJS is a great framework that allow separation of concerns pattern, if you’re new to AngularJS, maybe you need to learn differences between JQuery and AngularJS i’ve explained here https://creativcoders.wordpress.com/2014/05/11/differences-between-jquery-and-angularjs/.
For this first tdd with Angular, we just want a simple directive to indicate in our menu what our current route is. We can declare what we want in our view:
//View in the html
//<a href="/hello">Hello</a>
//Test begins here:
it( 'should add "active" when the route changes', inject(function() {
var elm = $compile( '<a href="/hello">Hello</a>' )( $scope );
$location.path('/not-matching');
expect( elm.hasClass('active') ).toBeFalsey();
$location.path( '/hello' );
expect( elm.hasClass('active') ).toBeTruthy();
}));
If we run our test, it will fail because initial link has no class ‘active’. We can now declare a directive to add a class on urlChange without having to modify the html.
.directive( 'whenActive', function ( $location ) {
return {
scope: true,
link: function ( scope, element, attrs ) {
scope.$on( '$routeChangeSuccess', function () {
if ( $location.path() == element.attr( 'href' ) ) {
element.addClass( 'active' );
} else {
element.removeClass( 'active' );
}
});
}
};
});
Well done for your first test driven development in AngularJS.