ng-click doesn't fire when added post load

后端 未结 3 2005
夕颜
夕颜 2020-12-19 02:40

I\'m trying to do a variable replacement while also making it clickable with ngClick.

I made a plunker demo (click the button and observe that the input box stays un

3条回答
  •  [愿得一人]
    2020-12-19 03:27

    Angular doesn't $compile the $sce markup. So Angular hasn't processed your ng-click and attached the directive to it.

    In order to use Angular directives inside your string, and have them live, you'll need to send the string to Angular's $compile function.

    One easy way to do this is to use the following directive (found here:https://github.com/angular/angular.js/issues/4992)

    Using this you'll replace:

    with

    And add this directive:

    angularApp.directive('compile', function($compile) {
      // directive factory creates a link function
      return function(scope, element, attrs) {
        scope.$watch(
          function(scope) {
            // watch the 'compile' expression for changes
            return scope.$eval(attrs.compile);
          },
          function(value) {
            // when the 'compile' expression changes
            // assign it into the current DOM
            element.html(value);
    
            // compile the new DOM and link it to the current
            // scope.
            // NOTE: we only compile .childNodes so that
            // we don't get into infinite loop compiling ourselves
            $compile(element.contents())(scope);
          }
        );
      };
    

    });

提交回复
热议问题