angularjs在ngBindHtml指令中单击事件

时间:2016-03-29 04:33:02

标签: angularjs ng-bind-html

我有一个angularjs示例代码段here,我可以使用ng-bind-html指令绑定html标记。但是如何在ngBindHtml指令中包含一些其他标签,如angularjs ng-clickid标签等,如

<a href="javascript:void(0);" id="myLink" ng-click="myFunct()">Test</a>

我的示例代码在这里:

var app = angular.module("myApp", ['ngSanitize']);
app.controller("myCtrl", function($scope) {
    $scope.myText = "<a href='#' ng-click='someFunction()'>Test</a>";

    $scope.someFunction = function(){
    alert("Link Clicked");
    };
});

仅供参考,数据是从服务器端脚本动态加载的,我必须在ng-bind-html指令内使用ng-repeat,我必须将相应的id传递给像ng-click="myFunction(x.id)"这样的点击事件。 sample 2

1 个答案:

答案 0 :(得分:2)

正如@Dr Jones建议的那样,您需要使用angular.module('ExampleApp', []) .controller('ExampleController', function($scope) { $scope.myText = "<button ng-click='someFunction(1)'>{{text}}</button>"; $scope.text = "Test"; $scope.someFunction = function(val) { console.log(val); }; }) .directive('bindHtmlCompile', function($compile) { return { restrict: "A", scope: { bindHtmlCompile: "=" }, link: function(scope, elem) { scope.$watch("bindHtmlCompile", function(newVal) { elem.html(''); var newElem = angular.element(newVal); var compileNewElem = $compile(newElem)(scope.$parent); elem.append(compileNewElem); }); } }; });指令。

jsfiddle上的实例。

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">
    <h3>
  Write code for test button
  </h3>
    <textarea cols="100" ng-model="myText"></textarea>
    <div bind-html-compile="myText">

    </div>
  </div>
</div>
{{1}}