angularjs $compile 重复问题

代码如下

<div id="ttt">
</div>

<script type="text/javascript">
    var MetronicApp = angular.module("MetronicApp", []);

    MetronicApp.controller('AppController', ['$scope', '$compile', function ($scope,$compile) {
        var As = $("#ttt").html("<button ng-click='ttfun()'> this click</button>");

        $compile(As.contents())($scope);
        $compile(As.contents())($scope);
        $compile(As.contents())($scope);
        $compile(As.contents())($scope);

        $scope.ttfun = function(){
            console.log("---");
        }

    }]);

</script>

以上是代码片段截取,问题是我点击按钮时 会运行 ttfun 函数 4次,就是绑定了点击事件四次,能不能配置它只能绑定一次,就是无论 $compile 运行多少次,后当点击按钮的时候只运行ttfun()一次

阅读 3.5k
2 个回答

为什么要写这么复杂的代码呢?这个地方好像是compile就会执行一次。

不知道你为什么要这样写,不过既然你只要运行一次,可以这样

var As = $("#ttt").html("<button type='button'  ng-click='ttfun()'> this click</button>");
$compile(As.contents())($scope);
$compile(As.contents())($scope);
$compile(As.contents())($scope);
$compile(As.contents())($scope);
var running = false;
$scope.ttfun = function(){
    if(running) return;
    running = true;
    console.log("---");
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题