AngularJS字符串替换和$ compile

时间:2018-03-01 16:29:19

标签: angularjs angularjs-directive angularjs-filter angularjs-compile

AngularJS新手 - 我正在尝试创建一个查找特定文本“标记”的函数,用绑定到控制器上某个函数的ng-click指令替换它们。例如,从我的数据库中我有很多文本字段,如下所示:

<p>Your [labor] cost is included in price</p>

我想这样结束:

<p>Your <a href="#" ng-click="showModal('labor')">labor</a> cost is included in price.</p>

使用过滤器替换[labor]令牌没有问题,但我对如何合并$compile以将ng-click绑定到$scope.showModal()我感到有些迷茫控制器。

任何帮助将不胜感激。谢谢。

我现有的过滤器:

myApp.filter('parseHtml', function ($sce) {

    return function (text) {

        var link = '<a href="" ng-click="getModal(\'labor\')">Labor</a>';
        var replaced = text.replace(/\[labor\]/g, link);

        return $sce.trustAsHtml(replaced);
    };
});

在html中

<span ng-bind-html="package.price | parseHtml"></span>

控制器

myApp.controller('MainController',
    function MainController($scope, $http) {

        $scope.getpackage = function (slug) {

            var onpackageComplete = function (response) {
                $scope.package = response.data;
            };
            $http.get('/packages/api/' + slug + '/detail')
                .then(onpackageComplete);
        };

        $scope.getModal = function (name) {

            $scope.modalVisible = true;
            if (name === 'labor') {
                $scope.modalBody = '/path/to/html/snippet/ModalLabor.html';
            } else if (name === '') {
                $scope.modalBody = '';
            }

        };
    }
);

1 个答案:

答案 0 :(得分:1)

Compiling dynamic HTML strings from database中提供的接受答案为参考,这应该可以解决问题

更改指令的过滤器,它使用令牌获取内容,将其替换为click函数并编译内容,再次放入DOM。请仔细阅读下面的演示,了解如何操作。

angular
  .module('app', [])

  //The new directive! (which replaced the old filter)
  .directive('parseHtml', function($compile) {
    return {
      restrict: 'A',
      replace: true,
      link: function(scope, iElem, attrs) {
        var link = '<a href="" ng-click="getModal(\'labor\')">Labor</a>';

        scope.$watch(attrs.parseHtml, function(text) {
          if (text) {
            var replaced = text.toString().replace(/\[labor\]/g, link);
            iElem.html(replaced);
            $compile(iElem.contents())(scope);
          }
        })
      }
    }
  })

  //sample controller
  .controller('MainController',
    function MainController($scope, $http) {
      var p = 1;
      
      $scope.getpackage = function() {debugger;
        $scope.package = {
          price: "Value is " + p + " hundred - [labor]"
        };
        p = p + 1;
      };

      $scope.getModal = function(name) {
        console.log('getModal clicked!');
        alert('getModal clicked!');
      };
    }
  );
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="MainController">

  <!--mock request-->
  <button ng-click="getpackage()"> Get Package</button> <br /> <br />

  <!-- how to use the directive -->
  <span parse-html="package.price"></span>

</div>

重要:链接中的操作为getModal(在指令中已修复)。如果需要,也可以动态添加,也需要将该函数作为参数传递给指令。新的实施需要一些改变。