在这里,我为按钮点击创建了示例角度程序。但它没有解雇 我可以知道我错在哪里吗?谁可以帮我这个事.. 感谢
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $sce) {
$scope.buttonHtml = $sce.trustAsHtml("<button ng-click='showMessage(\"foo\")'>click me</button>");
$scope.showMessage = function(message) {
alert(message);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-bind-html="buttonHtml"></div>
</div>
答案 0 :(得分:2)
问题在于,即使html呈现得很好,Angular也没有真正将ng-click
绑定到scope
,为此,首先必须$compile
。
var compiledHtml = $compile("<button ng-click='showMessage(\"foo\")'>click me</button>")($scope);
答案 1 :(得分:0)
你需要编译&amp;使用正确的范围链接元素并替换&#34;旧元素&#34;。这应该用一个指令来完成:
HTML:
<div ng-app="myApp" ng-controller="MyCtrl">
<div replace-with-compiled-html="buttonHtml"></div>
</div>
JS:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.buttonHtml = "<button ng-click='showMessage(\"foo\")'>click me</button>";
$scope.showMessage = function(message) {
alert(message);
}
});
myApp.directive('replaceWithCompiledHtml', function($compile) {
return {
compile: function compile(tElement, tAttrs, transclude) {
return {
post: function preLink(scope, elem, iAttrs, controller) {
// use the inherited scope -> get the wanted property via the attributes
var scopePropName = iAttrs['replaceWithCompiledHtml'];
// compile the html
var linkingFunc = $compile(scope[scopePropName]);
// link it with the correct inherited scope
linkingFunc(scope, function(newElem) {
// replace the new compiled element with the previous one
elem.replaceWith(newElem);
});
}
};
}
}
});