好的,所以问题在于它不会编译您包含的html(Angular不会解析它以查找指令等)。想不出一种方法可以从控制器内部进行编译,但是您可以创建一个包含内容的指令,然后对其进行编译。
所以你会改变
<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;
});
Angular1.2.12:http://jsfiddle.net/7k8xJ/4/
Angular1.4.3:http://jsfiddle.net/5g6z58yy/(与以前的代码相同,但有人说它在1.4上不起作用。*)