在angular js中找到多个###并替换为多个文本框

Find multiple ### and replace with multiple textbox(s) in angular js

本文关键字:替换 文本 angular js      更新时间:2023-09-26

我有这样的输入原始数据:

`###` train should I take to get to Kuala `###`, please?

需要将###以索引方式转换为文本框。

我怎么能做到呢?我期望的输出是:

<input type="text" ng-model="inputTextFIB[index]" class="input-textbox-fill-in-the-blank ng-pristine ng-untouched ng-valid ng-empty"> train should I take to get to Kuala <input type="text" ng-model="inputTextFIB[index]" class="input-textbox-fill-in-the-blank ng-pristine ng-untouched ng-valid ng-empty">, please?

注意:

inputTextFIB[index]:- 索引创建了多少###

谢谢你的帮助

angular
  .module('myApp', [])
  .run(function($rootScope) {
    $rootScope.title = 'myTest Page';
  })
  .controller('testController', ['$scope', '$sce',
    function($scope, $sce) {
      var counter = 0;
      $scope.myName = '### train should I take to get to Kuala ###, please?';
      var count = ($scope.myName.match(/###/g) || []).length;
      $scope.myName = $sce.trustAsHtml($scope.myName.replace(/###/g, function(x) {
        counter = counter + 1;
        return '<input type="text" ng-model="inputTextFIB' + counter + '" class="input-textbox-fill-in-the-blank ng-pristine ng-untouched ng-valid ng-empty">'
      }));
      $scope.call = function(value) {
        alert(value);
      }
    }
  ]).directive('compileTemplate', function($compile, $parse) {
    return {
      link: function(scope, element, attr) {
        var parsed = $parse(attr.ngBindHtml);
        function getStringValue() {
          return (parsed(scope) || '').toString();
        }
        //Recompile if the template changes
        scope.$watch(getStringValue, function() {
          $compile(element, null, -9999)(scope); //The -9999 makes it skip directives so that we do not recompile ourselves
        });
      }
    }
  });
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
  <link rel="stylesheet" href="style.css">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
  <script src="script.js"></script>
</head>
<body data-ng-controller="testController">
  <button ng-click="call(inputTextFIB2)">get</button>
  <p ng-bind-html="myName" compile-template></p>
</body>
</html>

多亏了Angular js中$ scene . trustashhtml()字符串中的调用函数。