简体   繁体   中英

Using Directive to Inject HTML with Directives and Data-Binding with AngularJS

I have a list that is populated with ng-repeat. I then have a directive that formats the content based on the content type field. I want to add directives on the injected HTML. How is this possible? Below is my code. The second statement in the if statement is not working (with ng-bind).

angular.module('mobileDashboardApp')
  .directive('detailFormat', function () {
    return {
      link: function postLink(scope, element, attrs) {
          var entry = scope.entry;
          if(entry.type === 'action') {
              element.append('<button>' + entry.value + '</button>');
          } else if (entry.type === 'event') {
              element.append('<button ng-bind="entry.value"></button>');
          } else if(entry.type === 'comment') {
              element.append('<strong>Note:</strong> ' + entry.value);
          }

      }
    };
  });

Why are you not using the markup in HTML for this?. Generally it is a terrible idea to manipulate the DOM yourself when using frameworks like Angular and Ember because they may trample all over your changes and get confused as to what has been rendered.

you can use some of the powerful template constructs to do this like ng-if.

<div ng-if="entry.type === 'action'">put something here<div>
<div ng-if="entry.type === 'event'">put something here<div>
<div ng-if="entry.type === 'comment'">put something here<div>

Hope this is helpful.

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