AngularJS:从模板设置textarea的值

时间:2014-10-16 16:19:03

标签: angularjs

在我的应用程序中,用户可以选择发送确认消息。此消息是使用默认值(取决于其他某些上下文)预生成的,但应由用户编辑。

在angularJS中,意图是预生成的消息来自模板。所以例如我会有Msg1.html和Msg2.html,每个都包含MsgCommon.html(可能使用ng-include)。然后使用当前作用域插入生成的文件,以提供预生成消息的文本版本,我可能会将其放入文本区域。

但我还没有找到如何用angularJS做到这一点。 AngularJS正确地处理了内容,因此我不能在其中放入ng-include。并且可能在textarea上应该有一个ng-model,所以我需要在处理模板后在我的控制器中初始化模型元素。以下几乎可行:

$http.get('msg1.html', {cache: $templateCache}).then(function(resp) {
   $scope.msg = $interpolate(resp.data)($scope);
});

in html:
<textarea ng-model='msg'></textarea>

这正确地插入了像{{...}}这样的字符串,但不会处理像ng-repeat或ng-include这样的指令。我想我需要使用某种形式的$ compile,但这需要一个DOM字符串或元素,而我的消息不是HTML。

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

此解决方案仅用于演示目的。我不建议在现实世界中使用它。我认为最好只使用$interpolate并在控制器中创建必要的逻辑。 (即。而不是使用ng-repeat,您可以在控制器中连接列表并插入此字符串)

这个丑陋的解决方案的想法是编译模板并使用元素的innerText来仅获取纯文本(Plunker):

$templateRequest('msg1.html').then(function(resp) {
  var el = angular.element('<div></div>');
  var templateScope = $scope.$new();

  templateScope.name = 'Foo'

  templateScope.tasks = ['t1', 't2', 't3', 't4'];

  el.html(resp);
  $compile( el.contents() )( templateScope );

  setTimeout(function(){
    $scope.msg = el[0].innerText;
    $scope.$apply();
  }, 10);
});
相关问题