AngularJS ng-click不会触发



i从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点击添加到已经在网站上的"静态"元素中时,一切都可以。

我必须关心这有效的作用?

谢谢

是的... $ 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>

,或者您也可以在控制器中注入$编译。

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

最新更新