16

I am using a scope method in an angular ng-click directive like so:

<a ng-click="$navigate.go('#/path/obj.val1/obj.val2')">{{obj.val1}}, {{obj.val2}}</a>

The trouble here is that obj.val1 and obj.val2 are interpreted as part of the string passed to the method in the expression. I need them to be evaluated as the variables that they are... I'm not sure what the right approach is here.

Is there an angular way to concat these values into that string/expression?

Am I simply "doing it wrong"?

||||||
2

It's not very clear what the problem is and what you are trying to accomplish from the code you posted, but I'll take a stab at it.

In general, I suggest calling a function on ng-click like so:

<a ng-click="navigateToPath()">click me</a>

obj.val1 & obj.val2 should be available on your controller's $scope, you dont need to pass those into a function from the markup.

then, in your controller:

$scope.navigateToPath = function(){
   var path = '/somePath/' + $scope.obj.val1 + '/' + $scope.obj.val2; //dont need the '#'
   $location.path(path)       
}
||||||
9

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});
||||||
  • Can you point to the documentation where this is defined? Thanks. :) – TyMayn Sep 15 '15 at 5:34
5

You can just concat the values using +

<a ng-click="$navigate.go('#/path/' + obj.val1 + '/' + obj.val2)">{{obj.val1}}, {{obj.val2}}</a>

Simple example on jsfiddle

I am sure the code you posted is a simplified example, if your path building is more complex I would recommend extracting out a function (or service) that would build your urls so you can effectively write unit test.

||||||
1
<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>
||||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.