Tuesday, March 4, 2014

ng-click on an anchor tag = pain

What do you do when things goes snap in AngularJS?
Here is the controller code:

var Controllers = angular.module('Controllers', ['ngRoute']);
Controllers.config(
function ($routeProvider){
$routeProvider
.when('/', {
controller: 'PalletListCtrl',
templateUrl: '/closeAndUplift_palletList.html'
})
.when('/edit/:id', {
controller: 'PalletEditCtrl',
templateUrl: '/closeAndUplift_palletEdit.html'
})
.when('/add', {
controller: 'PalletEditCtrl',
templateUrl: '/closeAndUplift_palletEdit.html'
})
.otherwise({
redirectTo: '/'
});
}
);

Controllers.controller('PalletListCtrl',function ($scope, $location, $route){
   console.log($route);
$scope.addPallet = function(){
$location.path('/add');
};
});
Controllers.controller('PalletEditCtrl', function ($scope, $location, $routeParams, $route){
    console.log($route);
});

And the HTML:



Well it doesn't look that difficult to me.
closeAndUplift_palletList.html loads and addPallet fires. This makes closeAndUplift_palletEdit.html download from the server, but nothing renders on the screen. At this point what do you do? How do you debug it?
Well, if you do go the debug route you step through $location.path('/add'); and end up in the digest portion looking at a comment;
//Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!

At this point you think to yourself that it might be a good day to go fishing.

The problem turned out to be the click event.
The addPallet was called like this...
<a class="round button" href="#" ng-click="addPallet()">Add</a>
Changing to 
<button class="round button" href="#" ng-click="addPallet()">Add</button>
resolved the problem.

So the problem wasn't with Angular but rather an inability to debug the way a browser loads/reloads pages. The problem is you can't return false from the ng-click to block the default anchor action.

No comments: