从动态文本中呈现指令

时间:2015-03-31 01:12:15

标签: angularjs angularjs-directive

我正在尝试使用从动态文本加载的自定义指令,'直到现在我已经创建了指令,如果我在HTML文件中使用此指令有效,但我想要做的是使用此指令模型(字符串)。

这是一个样本

https://jsfiddle.net/4Lg42e9d/2/

<div ng-app="test">

    <div class="holder" ng-controller="MainController">

        <div class="question">
            <label ng-bind-html="saveHtml">{{saveHtml}}</label><br>
            <input type="text" ng-model="current.answer">
        </div>

        <button ng-click="goNextQuestion()">Next</button>

        <hr>

            <answer></answer>

            <br>
            <br>
            <div>{{config}}</div>

    </div>

</div>

js file:

'use strict';

var app = angular.module('test', ['ngSanitize']);

app.controller('MainController', function($scope, $sce){

    var index = 0;

    $scope.config =  [
        {
            "id": "uniqueIdOne",
            "question": "What is your name?",
            "answer" : ""
        },
        {
            "id": "uniqueIdTwo",
            "question": "Great <answer></answer>, <strong>this is some random text</strong>.",
            "answer": ""
        }
    ];

    $scope.goNextQuestion = function(){
        $scope.current = $scope.config[++index];
        $scope.trustHtml();
    }

    $scope.trustHtml = function(){
        $scope.saveHtml = $sce.trustAsHtml( $scope.config[index].question );
    }

    $scope.current = $scope.config[0];
    $scope.trustHtml();


});

app.directive('answer', function() {
    return {
        template: 'This is rendered by the directive answer.',
    };
});

我可以使用指令加载文本,但不要呈现内容。

问题是:我如何触发指令渲染?

提前致谢!

1 个答案:

答案 0 :(得分:0)

你应该创建一个指令,用里面的指令编译文本。

使用$ compile服务,这样就可以触发指令渲染,如:

<强> JS

app.directive('myDirective',[ '$compile', function($compile){
      return {
        restrict: 'A',
        link: function($scope, iEle, attrs){
          var compiledTpl;
          function destroyData() {
            if (compiledTpl) {
              compiledTpl.remove();
              compiledTpl = null;
            }
            if ($scope.$newScope) {
              $scope.$newScope.$destroy();
              $scope.$newScope = null;
            }
          }

          $scope.$watch(attrs.myDirective, function (tpl) {
            destroyData();
            if (tpl) {
                tpl = '<div>' + tpl + '</div>';//make sure tpl is a html template.
                $scope.$newScope = $scope.$new();
                compiledTpl = $compile(tpl)($scope.$newScope);// compile the directive in string (trigger the directive render).
                iEle.append(compiledTpl);
            } else {
              iEle.html('');
            }
          });

          $scope.$on('$destroy', destroyData);//avoid memory leak.

        }
      };
    }]);

<强> HTML

<div my-directive="config[1].question"></div>

链接演示:https://jsfiddle.net/kw04qrdb/