【问题标题】:Is it possible to inject ng-click to an ng-binded html div in angular?是否可以将 ng-click 注入到 ng 绑定的 html div 中?
【发布时间】:2018-01-11 22:01:32
【问题描述】:

我正在使用此功能从我的控制器发送回 html:

$scope.filterLocation=function(obj){
 var loc = $filter('filter')( $scope.locationss, {'product_code':obj});
 var htmlstring = "";
 angular.forEach(loc, function(value, key) {
    htmlstring = '<div ng-click="locationModal()">' + htmlstring + value.location_description + '</div>';
 })

 return $sce.trustAsHtml(htmlstring);

}

然后我有这个 html 来显示位置列表:

<td><span ng-bind-html="filterLocation(l.productcode)" style="cursor: pointer;"></span></td>

问题是,正如您在控制器中看到的那样,我正在注入 '&lt;div ng-click="locationModal()"&gt;',当我查看检查器时,该功能是正确的:

<span ng-bind-html="filterLocation(l.productcode)" style="cursor: pointer;" class="ng-binding"><div ng-click="locationModal()">A5AL</div></span>

但是当我尝试单击它时,我没有得到任何结果,是因为它在 ng-bind-html 内吗?它是一个 div,但我将它更改为一个跨度,看看是否有任何改变。

【问题讨论】:

  • $compile 将使用scope 将字符串转换为DOM(因此可以使用ng-click
  • 使用它只是返回函数虽然我确实尝试使用 $compile,但无法让它工作
  • 您应该使用$compile 编写一个指令,然后将其放置在您的&lt;span&gt; 上,并使用$sce.trustAsHtml。这是一个有效的plunker 示例(或这个neat version with filters too
  • 我不能那样做,因为它在一个 ng-repeat 中,设置一个 $scope.html 不能作为这个选项......它需要在一个返回的函数中

标签: javascript html angularjs


【解决方案1】:

我目前正在快速执行此操作,但希望您能得到答案。

你可以做一些这样的解决方法:

$scope.htmlstrings = [];
var string = {
    htmlLoc: ''
};

angular.forEach(loc, function(value, key) {
    string.htmlLoc= string.htmlLoc+ value.location_description;
    $scope.htmlstrings.push(string);
})

我不明白你为什么这样做htmlstring = htmlstring + value.location_description; tho。

然后:

<span ng-init="filterLocation(l.productcode);" ng-repeat="htmlstring in htmlstrings">
    <div ng-click="locationModal();" ng-bind="htmlstring.htmlLoc"></div>
</span>

您可以将其更改为返回方式:&lt;span ng-init="htmlstrings = filterLocation(l.productcode);" ng-repeat="htmlstring in htmlstrings"&gt;

并且不使用var string = {}var string = '' html 看起来像这样:

<span ng-init="htmlstrings = filterLocation(l.productcode);" ng-repeat="htmlstring in htmlstrings">
    <div ng-click="locationModal();" ng-bind="htmlstring"></div>
</span>

我稍后会开发这个。希望它适用于您的情况。

【讨论】:

    猜你喜欢
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2016-04-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多