如何在angular js中使用指令.不适用于我的情况,为什么

How to use directive in angular js. Not works in my case, why.?

本文关键字:适用于 不适用 我的 情况 为什么 指令 angular js      更新时间:2023-09-26

我需要打印带有点击功能绑定的动态html。我已经使用了$sce.trustAsHtml分配给一个作用域变量。以下是我的代码供参考。我不明白为什么指令在我的情况下不起作用。请帮我解决这个问题。

app.js

angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
    .config(function($stateProvider, $urlRouterProvider) {
        .state('groupchat', {
          url: '/groupchat',
          templateUrl: 'templates/groupchat.html',
          controller: 'GroupChat',
          controllerAs: 'GC'
        })
    })
    .run(function($rootScope, $location, SharedProperties) {
      SharedProperties.sharedObject = {
        unread: 0,
        subscriptions: [],
      }
    });

groupchat.js//-控制器

angular.module('starter.controllers')
.directive('dynamic', function ($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, ele, attrs) {
          scope.$watch(attrs.dynamic, function(html) {
            ele.html(html);
            $compile(ele.contents())(scope);
          });
        }
      };
    })
.controller('GroupChat', function($rootScope, $scope, $sce, $compile) {  
    $scope.trustedHtml = $sce.trustAsHtml('<span ng-click="testAlert()">Submit</span>');  
    $scope.testAlert = function () {
        alert('testing');
    };
});

groupchat.html

<ion-view>
    <div dynamic="trustedHtml"></div>
</ion-view>
<div dynamic= "{{trustedHtml}}"> ??

我在想,如果这是问题所在,它将绑定字符串"trustedHtml",而不是hte-var内容,并且它将在您的情况下仍然工作/显示,但是