I\'ve got an angular app like:
angular.module(\'ngStyleApp\', [])
.controller(\'testCtrl\', function($scope) {
$scope.list = [1,2,3];
$scope.getStyles
This is the code of the ngStyle directive:
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
Notice that there is a scope.$watch for attr.ngStyle, that watch is what is making it trigger twice.
For instance, if you try to do the same thing using ngInit, you will notice that the function only gets called once. Now, lets have a look at the code of the ngInit directive, it looks like this:
var ngInitDirective = ngDirective({
priority: 450,
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
};
}
});
Notice that there is no watch in this directive.