$ compile在递归函数中不起作用

时间:2016-01-02 13:31:38

标签: javascript angularjs

我的JavaScipt代码:

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope, $compile) {
    $scope.number=10;
    $scope.init = function(i) {
        var element = angular.element(document.querySelector('#play'));
        var el = '<h1>{{number}}</h1>';
        el += '<h1>'+i+'</h1>';
        var generated = element.html(el);
        $compile(generated.contents())($scope);
        if(i==0) {
            return false;
        }
        setTimeout($scope.init, 1000, i-1);
    }
});

第一次调用函数init时{{number}}它显示为10,但是当再次调用函数init()时,$ cope.number显示为{{number}}。我的问题是:为什么$ compile不能正常工作?

1 个答案:

答案 0 :(得分:1)

DEMO http://plnkr.co/edit/ot2CNgUzZoZgIBsgMuCF?p=preview

试试这个:

var app = angular.module("myApp", []);

app.controller("mtCtrl", function($scope, $compile, $timeout) {
    $scope.number=10;
    $scope.init = function(i) {
        var element = angular.element(document.querySelector('#play'));
        var el = '<h1>{{number}}</h1>';
        el += '<h1>'+i+'</h1>';
        var generated = element.html(el);
        $compile(generated.contents())($scope);
        if (i === 0) {
            return false;
        }
        $timeout(function () {
          $scope.init(i-1);
        }, 1000);
    };
    $scope.init(10);
});