找到多个###并用角度js中的多个文本框替换

时间:2016-11-01 06:10:04

标签: javascript angularjs

我有这个输入原始数据:

`###` 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]: - index 根据找到###的数量创建。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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>

感谢call function inside $sce.trustAsHtml() string in Angular js指令。