gpt4 book ai didi

javascript - Angularjs ng-repeat 新元素

转载 作者:行者123 更新时间:2023-11-30 12:39:43 26 4
gpt4 key购买 nike

我正在尝试在 anguar.js 中制作一些测试应用程序,但遇到了问题。我的 js 文件包含:

live = angular.module('live',[]);
live.controller('printCtrl', function() {
this.test = [];
var thizzz = this;

this.getTest = function() {
return this.test;
};

setInterval(function() {
thizzz.test.push(Date.now());
}, 1000);
}
);

我的 html 文件包含:

<div class="content" ng-app="live">
<div ng-controller="printCtrl as print">
<div ng-repeat="t in print.getTest()">
{{t}}
</div>
</div>
</div>

但我什么也没看到。为什么?

------------更新----------------

我要像这样更改我的 js 文件:

live = angular.module('live',[]);
live.controller('printCtrl', function() {
this.test = [1, 2, 3];
var thizzz = this;

this.getTest = function() {
console.log('INSIDE');
return this.test;
};

setInterval(function() {
thizzz.test.push(Date.now());
}, 1000);
}
);

和 html 没有任何变化。

我在 HTML 文件中没有看到任何想法,但我在控制台中看到,angular 如何调用 2 次 getTest 函数。

最佳答案

如果我们在 AngularJS 应用程序中使用 setIntervalsetTimeout 我们还需要使用 $scope.$apply() 来确保对作用域的任何更改都会被反射(reflect)出来其他地方(即 View 中的数据绑定(bind))。

AngularJS 为此提供了一个方便的包装器:$timeout() - 它为我们执行 $apply() 调用,因此我们不必这样做。

$interval(function () {
thizzz.test.push(Date.now());
}, 1000);

查看演示:http://jsfiddle.net/VPVF6/

关于javascript - Angularjs ng-repeat 新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24885714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com