0

This plunk refers.

I have two simple element (restrict: "E") directives, incButtonOne and incButtonTwo, that track and display the number of times it has been clicked. They both implement local controllers and have isolate scope. The two directives accomplish the same thing but with slightly different implementations:

  • incButtonOne's template includes a ng-click directive in the tag to facilitate the click counting by calling a function in the directive's controller
  • incButtonTwo implements a link function to register a click event handler that calls the incrementing function in the directive's controller

They both work. Kind of. The problem is that incButtonTwo's displayed value is only updated after incButtonOne is clicked, i.e. the value is in fact updated (this can be confirmed by uncommenting the alert statement on line 45) but it's not being displayed until some other action is performed.

I would just like to understand why this is happening and how to fix it. Thanks!

2 Answers 2

1

As Stanislav Demydiuk said, you must use $apply() to get your binding to update. And using your function "increment", here is what you get:

element.on("click", function() {
     scope.$apply(increment);
});

Note: In your example, if the click on the first button makes your second button update, it's because of ng-click event, which is wrapped in $scope.$apply() (see this article).

Sign up to request clarification or add additional context in comments.

Comments

0

When you manually register event handler you must manually call scope.$apply() function like this

link: function(scope, element) {
  element.on('click', function() {
     scope.$apply(function() {
        scope.count++;
     });
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.