简体   繁体   中英

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

I have a HTML code I am dynamically changing based on the navigation stack. I am using ng-bind-html to insert the string containing the code into the view. Now I need to be able to input the ng-click attribute into the view too. Everything is OK except the ng-click attribute does not get injected and hence I am unable to quickly navigate in the breadcrumbs.

Here is the HTML I am passing to the view:

$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>';

The class gets applied but the ng-click attribute gets simply ignored. What am I missing? Thanks.

If you look at ng-bind-html API you will come to know that it only parse the html & append it as text to the DOM using element.text . The html has added will not have any compile'd angular DOM. It will work as normal markup.

I'd suggest your own directive to handle breadcrumb stuff by putting it on breadcrumb element. So that you can get control over that DOM inside directive link function. After creating your breadcrumb html you need to compile that html first and then append it to breadcrumb DOM using $compile service.

Code

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))
}

From the syntax of breadcrumbs it looks like it can be replaced with simple ng-repeat and leaving html for the view layer ie

controller

  $scope.breadcrumbs.push(newCrumb)

where newCrumb would be an object with all the information you need

view

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM