AngularJS ng-click 没有触发

AngularJS ng-click doesn't fire

我从 json 文件动态生成一些标签,然后像这样将它们添加到页面中:

for(var i = 0; i < currentScene.hotpoints.hotpoint.length; i++)
{
  var hotpoint = currentScene.hotpoints.hotpoint[i];

  var pos = hotpoint.pos.split(";");

  var x = parseFloat(pos[0]) * multiplierX;
  var y = parseFloat(pos[1]) * multiplierY;


  htmlstring += '<a href ng-controller="main" id="hp'+ hotpoint.ID + '" class="hotpoint animated infinite" style="top: ' + parseInt(y) + 'px; left: ' + parseInt(x) + 'px;" ng-click="enterScene(' +hotpoint.sceneID + ',' + hotpoint.ID +')"></a>';

}
$scope.hotpoints = $sce.trustAsHtml(htmlstring);

效果很好。现在如您所见,我想为每个元素启用点击事件。所以我使用 ng-click。但它没有被解雇。

当我将此 ng-click 添加到网站上已有的 "static" 元素时,一切正常。

我需要关心的是这个有效吗?

谢谢

是的... $compile 应该用于此..

(function(){
"use strict";
angular.module("CompileDirective", [])
  .directive('dynamicElement', ['$compile', function ($compile) {
      return { 
        restrict: 'E', 
        scope: {
            message: "="
        },
        replace: true,
        link: function(scope, element, attrs) {
            var template = $compile(scope.message)(scope);
            element.replaceWith(template);               
        },
        controller: ['$scope', function($scope) {
           $scope.clickMe = function(){
                alert("hi")
           };
        }]
      }
  }])
  .controller("DemoController", ["$scope", function($scope){
      $scope.htmlString = '<div><input type="button" ng-click="clickMe()" value="click me!"/> </div>';
  }])

}());

与以下 HTML:

<div ng-controller="DemoController">
  <dynamic-element message='htmlString'></dynamic-element>
</div>

或者你也可以在控制器中注入 $compile..

app.controller('AppController', function ($scope, $compile) {

    var $el = $('<td contenteditable><input type="text" class="editBox" value=""/></td>' +
        '<td contenteditable><input type="text" class="editBox" value=""/></td>' +
        '<td>' +
        '<span>' +
        '<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>' +
        '</span>' +
        '</td>').appendTo('#newTransaction');
    $compile($el)($scope);

    $scope.create = function(){
        console.log('clicked')
    }
})

最简单的方法..

$("#dynamicContent").html(
  $compile(
    "<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
  )(scope)
);