Javascript 在AngularJS中将服务函数与ng绑定html一起使用

Javascript 在AngularJS中将服务函数与ng绑定html一起使用,javascript,angularjs,angular-services,ng-bind-html,Javascript,Angularjs,Angular Services,Ng Bind Html,我试图使用一个名为highlightReview的转换函数,该函数是在AngularJS服务中定义的,属性为ng bind html,但我无法使它工作 请参见下面的示例: function myReputationSrvc($http, $q, $log, $sce) { this.highlightReview = function(text) { return $sce.trustAsHtml(text); } } 然后在HTML中调用该函数,如下所示:

我试图使用一个名为
highlightReview
的转换函数,该函数是在AngularJS服务中定义的,属性为
ng bind html
,但我无法使它工作

请参见下面的示例:

function myReputationSrvc($http, $q, $log, $sce) {

    this.highlightReview = function(text) {
        return $sce.trustAsHtml(text);
    }
}
然后在HTML中调用该函数,如下所示:

<span ng-bind-html = " MyReputationSrvc.highlightReview(review.positiveText) "> </span>

没有调用任何内容,也没有抛出任何错误,似乎
ng bind html
只处理
$scope
上下文中的函数或变量,因为如果我将函数移动到
$scope
中,然后使用
ng bind html=“highlightReview(review.positiveText)”调用它,
工作正常

是否有办法使用服务中的功能我已将此功能放入服务中,因为我想在多个控制器之间共享此功能。


AngularJS版本为:1.6.5。

您需要将服务注入控制器并将函数放置在控制器中,您不能直接从模板调用服务函数

或者你可以用你自己的过滤器来做这项工作

.filter('mysce',function($http, $q, $log, $sce){  
     return $sce.trustAsHtml(text);
});

<span ng-bind-html = "review.positiveText | mysce"> </span>
.filter('mysce',function($http,$q,$log,$sce){
返回$sce.trustAsHtml(文本);
});

如果您想使其变得通用,而不是使用服务,您可以使用
过滤器

.filter('convertHtml',function($sce){
  return function(text){
     return $sce.trustAsHtml(text);
 }
})


<span ng-bind-html = "review.positiveText | convertHtml "> </span>
.filter('convertHtml',函数($sce){
返回函数(文本){
返回$sce.trustAsHtml(文本);
}
})
来自AngularJS文档:


如果您将
ngSanitize
注入您正在使用的模块,您只需使用
ngbind html
传递一个值为html的字符串参数。

您可以看看这个例子吗,因为您有一个示例代码片段

示例代码:

app.controller('MainCtrl', ['$scope', 'MyReputationSrvc', function($scope, MyReputationSrvc) {
  $scope.positiveText = "Hello </br> <b>World</b>";
  $scope.MyReputation = function(repText){
    return MyReputationSrvc.highlightReview(repText);
  };
}]);
app.controller('MainCtrl',['$scope','MyReputationSrvc',函数($scope,MyReputationSrvc){
$scope.positiveText=“你好
World”; $scope.MyReputation=函数(repText){ 返回MyReputationSrvc.highlightReview(repText); }; }]);
我建议使用基于
过滤器的解决方案,这非常优雅:.@sp00m如果我需要向函数传递两个参数而不是一个参数,该怎么办?假设文本和另一个参数,我还可以使用过滤器吗?我不确定我是否理解。你介意提供你的实际代码吗?我已经在控制器内注入了服务,我可以在控制器内使用其他函数,我自己也可以使用一个公共过滤器above@Sajeetharan你救了我的命hugs:如果我需要向函数传递两个参数呢?我还能用过滤器吗?那我怎么称呼它呢?你可以。检查这个