【问题标题】:Can I use interpolation in an Angular controller (not just in the HTML)?我可以在 Angular 控制器中使用插值(不仅仅是在 HTML 中)吗?
【发布时间】:2014-08-29 19:43:23
【问题描述】:

我有以下 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>

它采用用户输入的一些值并构建一个用户可以嵌入到其网站中的脚本(例如,按钮颜色、按钮标签、按钮样式等)。插值对此非常方便。

但是,我需要访问此插值字符串以供 data-clipboard-text 使用,以便将其复制到剪贴板。当前尝试使用 ng-model 绑定代码 sn-p 的方法不起作用。

我不希望必须使用普通的旧 JavaScript 连接在控制器中构建脚本标记,所以我想知道是否有一种方法可以使用插值来构建该字符串并将其添加到范围中。

我查看了 $interpolate 但我不确定这是否正是我需要的。 $interpolate 是否处理条件(如 {{button.label || 'Click Here'}})?

$compile 看起来也可能在这里相关,但我不确定如何将它们放在一起(对于 Angular 来说是新事物)。

希望这有点道理。感谢您的任何建议!

【问题讨论】:

  • 如果值可以被插值,它不是已经在你的控制器 $scope 上了吗?
  • 每个单独的值都是。但是,我希望在 Javascript 中我可以执行以下操作: $scope.sn-p = "

标签: javascript html angularjs interpolation


【解决方案1】:

根据您的评论,您可以:

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

【讨论】:

  • 正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 2013-03-21
相关资源
最近更新 更多