[javascript] concat scope variables into string in angular directive expression

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"?

This question is related to javascript angularjs

The answer is


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

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.


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;
  };
});