i'm trying make some test app in anguar.js, but faced with the problem. My js file contain:
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);
}
);
My html file contain:
<div class="content" ng-app="live">
<div ng-controller="printCtrl as print">
<div ng-repeat="t in print.getTest()">
{{t}}
</div>
</div>
</div>
But i don't see anything. Why?
------------- UPDATE ---------------
I'm change my js file like this:
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);
}
);
and html without any changes.
I don't see anythink in HTML files, but i see in console, how angular call 2 times getTest function.
If we use setInterval
or setTimeout
in an AngularJS application we also need to use $scope.$apply() to ensure that any changes to the scope will be reflected elsewhere (ie data-bound in a view).
AngularJS provides a handy wrapper for this: $timeout() - it does the $apply() call for us so we don't have to.
$interval(function () {
thizzz.test.push(Date.now());
}, 1000);
see demo: http://jsfiddle.net/VPVF6/
You need to init a variable first in order to get the list and then use that scope variable
<div class="content" ng-app="live">
<div ng-controller="printCtrl as print" ng-init="printList=getTest()">
<div ng-repeat="t in printList">
{{t}}
</div>
</div>
</div>
The controller is required to have $interval service so that no $apply is required
$interval(function() {
$scope.test.push(Date.now());
}, 1000);
please see here : http://jsbin.com/munal/2/edit
<div ng-controller="printCtrl" ng-init="printList=getTest()">
<div ng-repeat="t in test">
{{t}}
</div>
</div>
</div>
JS:
app.controller('printCtrl', function($scope){
$scope.test = [];
this.getTest = function() {
return this.test;
};
setInterval(function() {
$scope.test.push(Date.now());
$scope.$apply();
}, 1000);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.