如何允许用户在文本框中插入角度范围变量

How to allow users to insert angular scope variables into a text box

本文关键字:插入 范围 变量 何允许 用户 文本      更新时间:2023-09-26

我有一个这样的文本区域:

<textarea ng-model="content"></textarea>
{{content}}

还有一个像这样的变量:

$scope.name = 'Billy'

我想让用户能够将变量插入文本区域,这样,如果他们输入:

Hello {{name}}

{{content}}的输出可以是Hello Billy

我可能还想简化它,这样用户就可以在文本区域中键入类似于:Hello [Name]的内容,并以相同的方式进行解析。

这是一个plunker。https://plnkr.co/edit/0VH106Gxz7xjhCj5NMpT?p=preview

最好把这一点写在指令中。但这里是快速而肮脏的

app = angular.module('plunkr', []);
app.controller('messages', function($scope, $interpolate){
  $scope.name = 'billy';
  $scope.evalText = function(msg){
    console.log(msg)
    $scope.message = $interpolate(msg)($scope)
  }
});

如果我答对了问题,请尝试使用interpole。

代号james切中要害。但如果有人想在全球范围内使用它,他们可以扩展它来创建一个过滤器,如下所示。

<html ng-app="nameApp">
  <head>
  </head>
  <body ng-controller="NameCtrl">
      <textarea ng-init="content='Name is {{name}}'" ng-model="content"></textarea>
       {{content | compile:this}}
  </body>
</html>

具有以下Js:

var nameApp = angular.module('nameApp', []);
nameApp.controller('NameCtrl', function ($scope){
    $scope.name = 'John';
  });
nameApp.filter('compile', function($interpolate) {
  return function(input, scope) {
    return input ? $interpolate(input)(scope) : '';
  };
})

现场演示:http://codepen.io/anon/pen/RaZpaO