2015-03-31 31 views
0

我正嘗試使用從動態文本加載的自定義指令,直到現在我創建了該指令,並且如果我在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文件:

'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.', 
    }; 
}); 

我可以加載指令中的文本,但不呈現內容。

問題是:如何觸發指令渲染?

在此先感謝!

回答

0

您應該創建一個指令來編譯帶有指令的文本。

使用$編譯服務,讓您可以觸發指令渲染,如:

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/