Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 615
bakedbean Avatar asked Oct 04 '13 16:10

bakedbean


4 Answers

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;
  };
});
like image 141
Adam Avatar answered Nov 01 '22 14:11

Adam


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.

like image 22
Mark Coleman Avatar answered Nov 01 '22 15:11

Mark Coleman


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)       
}
like image 2
kmdsax Avatar answered Nov 01 '22 15:11

kmdsax


<a ngHref="/path/{{obj.val1}}/{{obj.val2}}">{{obj.val1}}, {{obj.val2}}</a>
like image 1
T A Avatar answered Nov 01 '22 15:11

T A