parliament parliament - 3 months ago 9x
AngularJS Question

using angular $compile for string replacement

endpointTemplate = "/api/endpoint?city={{city}}&state={{state}}&facility={{facility}}";
var model = angular.extend(scope.$new(), { city: 'Brooklyn', state: 'NY', facility: 'Facility 2' });
var compiled = $compile($('<a>',
//none of these work as i expect
'ng-href': endpointTemplate,
'test': endpointTemplate,
'ng-bind': endpointTemplate

var result = compiled(model);

I would like to get the value out like:

"/api/endpoint?city=Brooklyn&state=NY&facility=Facility 2"

But angular doesnt seem to leave the string "as-is" (except for the ng-bind attempt, which throws an error)

How can I make this work?


You may notice that result will became interpolated once digest cycle is over. It is inappropriate use for $compile if all that's required is string interpolation, consider using $interpolate instead, which

is used by the HTML $compile service for data binding.

It should be something like this:

var model = { city: 'Brooklyn', state: 'NY', facility: 'Facility 2' };

var result = $interpolate($('<a>', ...)[0].outerHTML)(model);