问题描述
我有我从JSON文件中加载一些HTML数据。
I have some html data that I'm loading in from a json file.
我在我的应用程序使用ngSanitize并采用NG-绑定-HTML显示该HTML数据。
I am displaying this html data by using ngSanitize in my app and using ng-bind-html.
现在,我想在JSON BLOB的任何链接转换标准
Now I would like to convert any links in the json blob from the standard
-
< A HREF =some_link>链接< / A>
<a href="some_link">link</a>
到
-
&LT;一个NG点击=GotoLink('some_link','_系统')&GT;链接&LT; / A&GT;
<a ng-click="GotoLink('some_link','_system')">link</a>
.
所以我做的JSON文件中的一些正则表达式的链接转换,但由于某些原因,但是NG-绑定,HTML是过滤掉NG单击它的输出,我想不通为什么。难道应该这样做,如果是的话是有可能禁用这种行为?
So I'm doing some regExp on the json file to convert the links, but for some reason however ng-bind-html is filtering out the ng-click in it's output, and I can't figure out why. Is it supposed to do this, and if so is it possible to disable this behavior?
看看这个对的jsfiddle演示:
Check out this jsFiddle for a demonstration:http://jsfiddle.net/7k8xJ/1/
任何想法?
推荐答案
好了,问题是,它是不是您编译包含HTML(角度不解析它找到指令和诸如此类的东西)。不能想办法让它从控制器中编译,但你可以创建一个指令,它包括的内容,并对其进行编译。
Ok, so the issue is that it isn't compiling the html you include (angular isn't parsing it to find directives and whatnot). Can't think of a way to make it to compile from within the controller, but you could create a directive that includes the content, and compiles it.
所以,你会改变
<p ng-bind-html="name"></p>
到
<p compile="name"></p>
和则对于JS:
var myApp = angular.module('myApp', ['ngSanitize']);
angular.module('myApp')
.directive('compile', ['$compile', function ($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.compile);
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
)};
}]).controller('MyCtrl', function($scope) {
var str = 'hello http://www.cnn.com';
var urlRegEx = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-]*)?\??(?:[\-\+=&;%@\.\w]*)#?(?:[\.\!\/\\\w]*))?)/g;
result = str.replace(urlRegEx, "<a ng-click=\"GotoLink('$1',\'_system\')\">$1</a>");
$scope.GotoLink = function() { alert(); }
$scope.name = result;
});
角1.2.12:
角1.4.3:(同一code和以前一样,但有些人说这不会对1.4工作。*)
Angular 1.4.3: http://jsfiddle.net/5g6z58yy/ (same code as before, but some people were saying it doesn't work on 1.4.*)
这篇关于角:NG-绑定-HTML过滤掉NG-点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!