2013-08-05 27 views
1

我的目標是從一段文字所有的主題標籤的提取和使用指導這個替換它們意味着它應該從這個去:Angularjs - 內置指令與NG綁定,HTML不安全

<p>Hello #stackoverflow this is a #test<p> 

<p>Hello <hashtag="stackoverflow"></hashtag> this is a #test<p> 

我的想法是使用過濾器來替換該指令HTML的主題標籤,但我不知道如何,因爲表現出來,NG綁定,HTML不安全犯規編譯指令明顯。

任何提示?

回答

6

創建一個新的指令,其追加到DOM編譯後的HTML字符串作爲模板:

angular.module('myCompile', [], ['$compileProvider', function($compileProvider) { 
    // Allows an attribute's value to be evaluated and compiled against the scope, resulting 
    // in an angularized template being injected in its place. 
    // 
    // Note: This directive is suffixed with "unsafe" because it does not sanitize the HTML. It is up 
    // to the developer to ensure that the HTML is safe to insert into the DOM. 
    // 
    // Usage: 
    //  HTML: <div my-compile-unsafe="templateHtml"></div> 
    //  JS: $scope.templateHtml = '<a ng-onclick="doSomething()">Click me!</a>'; 
    //  Result: DIV will contain an anchor that will call $scope.doSomething() when clicked. 
    $compileProvider.directive('myCompileUnsafe', ['$compile', function($compile) { 
    return function(scope, element, attrs) { 
     scope.$watch(
     function(scope) { 
      // watch the 'compile' expression for changes 
      return scope.$eval(attrs.myCompileUnsafe); 
     }, 
     function(value) { 
      // when the 'compile' expression changes 
      // assign it into the current DOM element 
      element.html(value); 

      // compile the new DOM and link it to the current 
      // scope. 
      // NOTE: we only compile .childNodes so that 
      // we don't get into infinite loop compiling ourselves 
      $compile(element.contents())(scope); 
     } 
    ); 
    }; 
    }]); 
}]);