我的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不能正常工作?
答案 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);
});