Reputation: 31
I am developing a mobile application and found that angularjs 1.1.4 has a ngTap directive available replacing standard ng-click. It makes app more robust, so I've decided to replace all my ng-href directive with ng-tap. For this purpose I've created a "go()" function available from $rootScope. The problem is that it can not resolve the url variable.
Here's my code.
$rootScope.go = function (url) {
$location.path(url);
}
and in template:
<a class="niceButtonLikeStyled" data-ng-click="go(/somewhere/var.id/)">{{ var.id }}</a>
Using data-ng-click as ngTap is portable and replaces ng-click if new ngMobile loaded. My problem seems to be with go() argument (mixing static & variable content ?
Maybe there's the other way of just binding new ng-click to all links.. or simply adding own directive that would take value from ng-href and made the location redirect and attach the ng-tap click event.
Upvotes: 1
Views: 12575
Reputation:
When you use ng-click, you're calling an AngularJS expression.
Your current code's expression is this:
go(/somewhere/var.id/)
You need to quote that string:
go('/somewhere/' + var.id + '/')
Another issue with your code: The function go
should be in the scope of the controller rather than in the $rootScope:
angular.module('MyModule').controller(
'MyController',
function ($scope, $location) {
$scope.go = function (url) {
$location.path(url);
}
}
);
Here's how your template would look:
<div ng-controller="MyController as mycontroller">
<a class="niceButtonLikeStyled"
data-ng-click="mycontroller.go('/somewhere/' + var.id + '/')">
{{ var.id }}
</a>
</div>
That's the biggest issue with the code, you're using $rootScope instead of putting the variables and functions you need in the scope of a controller where it belongs.
Upvotes: 3