在ng-bind-html中绑定ng-click::在HTML中绑定Angular属性

Bind ng-click in ng-bind-html :: Binding Angular attributes in the HTML

本文关键字:绑定 属性 Angular ng-click ng-bind-html HTML      更新时间:2023-09-26

我有一个基于导航堆栈动态更改的HTML代码。我使用ng-bind-html将包含代码的字符串插入视图中。现在我还需要能够在视图中输入ng-click属性。一切都很好,除了ng-click属性没有被注入,因此我无法在面包屑中快速导航。

这是我传递给视图的HTML:

$scope.breadcrumbs = $scope.breadcrumbs + '&nbsp;<i class="ion-ios-arrow-forward"></i>&nbsp;' + '<span ng-click="goToLevel(pathLength)" class="browse-breadcrumbs-link">' + $scope.title + '</span>';

类被应用,但ng-click属性被忽略。我错过了什么?谢谢。

如果你看看ng-bind-html API,你会知道它只解析html &使用element.text将其作为文本附加到DOM。添加的html不会有任何编译过的angular DOM。它将作为正常的标记。

我建议你自己的指令来处理面包屑的东西,把它放在breadcrumb元素。这样你就能在指令链接函数中控制DOM。创建breadcrumb html后,您需要首先编译该html,然后使用$compile服务将其附加到breadcrumb DOM。

link: function(scope, element, attrs){
   //you code would something like below..
   //create an html
   scope.breadcrumbs = scope.breadcrumbs + '&nbsp;<i class="ion-ios-arrow-forward"></i>&nbsp;' + '<span ng-click="goToLevel(pathLength)" class="browse-breadcrumbs-link">' + $scope.title + '</span>';
   element.empty();
   element.append($compile(scope.breadcrumbs)(scope))
}

从面包屑的语法来看,它看起来可以用简单的ng-repeat代替,并将html留给视图层,即

控制器

  $scope.breadcrumbs.push(newCrumb)

其中newCrumb是一个包含所有信息的对象

<<h3>视图/h3>
<span ng-repeat="crumb in breadcrumbs">
  &nbsp;<i class="ion-ios-arrow-forward"></i>
  &nbsp;<span ng-click="goToLevel(pathLength)" class="browse-breadcrumbs-link">{{crumb.title}}</span>
</span>