Paul Erdos
Paul Erdos

Reputation: 1375

Can I use interpolation in an Angular controller (not just in the HTML)?

I have the following HTML:

<i class="icon-copy" data-clipboard data-clipboard-text="{{codeSnippet}}" data-title="Click to copy the code to your clipboard" data-placement="top"></i>
<textarea class="code-snippet" ng-model="codeSnippet" readonly onclick="this.focus();this.select()">&lt;script src="{{scriptURL}}"&gt;&lt;/script&gt;&lt;button class="main-button" style="background-color:{{button.color || branding.color}};border-radius:{{button.skin.radius || '0'}};display:none;" data-id="{{product.id}}" data-key="{{key}}" data-color="{{button.color || branding.color}}"&gt;{{button.label || 'Click Here'}}&lt;/button&gt;</textarea>

It takes some values the user has entered and builds up a script the user can embed in their site (for instance, button color, button label, button styling, etc). The interpolation is really handy for this.

However, I need to access this interpolated string to be available to data-clipboard-text so that I can copy it to the clipboard. The current way of trying to bind the code snippet using ng-model isn't working.

I would hate to have to build up the script tag in the controller using plain old JavaScript concatenation so I was wondering if there is a way to use interpolation to build up that string and add it to the scope.

I looked at $interpolate but I'm not sure if that's exactly what I need. Does $interpolate handle conditionals (like {{button.label || 'Click Here'}})?

$compile also looks like it could be relevant here, but I'm not sure how to put it all together (newish to Angular).

Hope this makes a sliver of sense. Thanks for any suggestions!

Upvotes: 0

Views: 1020

Answers (1)

rvignacio
rvignacio

Reputation: 1740

Following your comment, you can do:

// Create a function to parse your input and return an interpolated string
var getter = $interpolate('<script ng-src="{{scriptURL}}"></script>');
var value = {
    scriptURL: 'myScript.js'
};
// Evaluate the template with your values and add it to the $scope.
$scope.snippet = getter(value);

Upvotes: 3

Related Questions