我有以下 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()"><script src="{{scriptURL}}"></script><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}}">{{button.label || 'Click Here'}}</button></textarea>
它采用用户输入的一些值并构建用户可以嵌入其网站的脚本(例如,按钮颜色、按钮标签、按钮样式等)。插值对此非常方便。
但是,我需要访问此内插字符串以供 data-clipboard-text 使用,以便我可以将其复制到剪贴板。当前尝试使用 ng-model 绑定(bind)代码片段的方法不起作用。
我不想使用普通的旧 JavaScript 连接在 Controller 中构建脚本标签,所以我想知道是否有一种方法可以使用插值来构建该字符串并将其添加到范围中。
我查看了 $interpolate 但我不确定这是否正是我所需要的。 $interpolate 是否处理条件(如 {{button.label || 'Click Here'}})?
$compile 看起来也可能与这里相关,但我不确定如何将它们放在一起(对于 Angular 来说是新的)。
希望这有一点道理。感谢您的任何建议!
最佳答案
根据您的评论,您可以执行以下操作:
// 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);
关于javascript - 我可以在 Angular Controller 中使用插值(不仅仅是在 HTML 中)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575179/