Reputation: 1620
I recently re-factored a bit of html into a directive. The original HTML had an ng-click attribute that called a function in the control and cleared out a data field. Its fast. But when I re-factored it into a directive, there is a lag between the button press and the clearing of the field.
.directive('evFilterbox', ['$parse', function ($parse) {
return {
restrict: "EA",
template: function (el, at) {
return "<div class=\"filterbox\">"
+ "<div class=\"input-group\">"
+ "<input id=\"input-"+ at.id +"\" class=\"form-control\" type=\"text\""
+ " tooltip=\"{{tt." + at.id + "}}\""
+ " placeholder=\"{{pp." + at.id + "}}\""
+ " ng-model=\"data." + at.id + "\">"
+ "<span id=\"span-"+at.id +"\" class=\"input-group-addon glyphicon glyphicon-remove\"></span>"
+ "</div></div>";
},
replace: true,
link: function (scope, element, attrs) {
$('#span-' + attrs.id).bind('click', function() {
scope.data[attrs.id] = '';
});
}
};
}])
Any comments on improving this directive are welcome.
Upvotes: 1
Views: 1262
Reputation: 2213
Change the link
function to this:
function (scope, element, attrs) {
$('#span-' + attrs.id).bind('click', function() {
scope.$apply(function () {
scope.data[attrs.id] = '';
});
});
}
This will make the $digest
loop run.
Upvotes: 3
Reputation: 4202
The lag is due to using jQuery (not that jQuery is slow).
Making a DOM change with jQuery does not start a $digest
cycle. It is not until something else in your angular app starts a $digest
that your view will be updated.
I recommend you either use ng-click
in your template, or add scope.$apply
:
$('#span-' + attrs.id).bind('click', function() {
scope.$apply(function() { // Starts a $digest.
scope.data[attrs.id] = '';
});
});
Upvotes: 0