Reputation: 1
I have a simple code:
angular.module('ui.bootstrap.demo', ['ui.bootstrap']);
angular.module('ui.bootstrap.demo').controller('CarouselDemoCtrl', function ($scope) {
$scope.myInterval = 5000;
var slides = $scope.slides = [];
$scope.addSlide = function() {
var newWidth = 600 + slides.length + 1;
slides.push({
image: 'http://placekitten.com/' + newWidth + '/300',
text: ['More','Extra','Lots of','Surplus'][slides.length % 4] + ' ' +
['Cats', 'Kittys', 'Felines', 'Cutes'][slides.length % 4]
});
};
for (var i=0; i<4; i++) {
$scope.addSlide();
}
$scope.sayHello=function(name){
//**function is call after carousel slide change image**
console.log('SayHello::',name);
angular.element(document.querySelector('#debugger')).append('::Call\r\n');
return "Hello " + name;
}
});
my function sayHello() always call after my carousel change slide. why?
I want sayHello() function called only once.
Thanks
Upvotes: 0
Views: 547
Reputation: 327
This is because of the angularjs databinding system. When a digest cycle runs, all the binding are evaluated. If any of those changed, then the digest process is runned again to re-evaluate the bindings with the new computed data.
This shows that a digest cycle never runs only once, it has to run at least twice.
In your view you have {{sayHello('BILL')}}
which prints the name passed in parameter. But what if this name came from an input that was modified, you'd like to have this name refreshed in your view.
The best practice is to have light process in your bindings and if you need some heavy process go throught a watch. When you register a watch, you say how angularjs should handle the call to the associated listner.
$scope.$watch('name', function(newValue, oldValue) {
// do some heavy process and update the DOM
});
At each digest cycle, angularjs will test the watchExpression and the listener function will be called only if the watchExpression return changes. In this case if the name value changed.
Upvotes: 1