我从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);
这很有效。现在,就像你看到我想为每个元素启用click事件。所以我使用ng-click。但它并没有被解雇。
当我将这个ng-click添加到&#34;静态&#34;已经在网站上的元素一切正常。
我必须关心这是否有效?
由于
答案 0 :(得分:3)
是的...... $ 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)
);