0

I have the following problem: I have a function inside a controller, and the function decides the value of a $scope.name

app.controller('myController', ['$scope', function($scope) {
    function myFunction() {
       $scope.name = 'myName';
    }
document.getElementById('my-id').addEventListener("click", myFunction);
}])

I cannot use ng-click for multiple reasons. UPDATE: I cannot use ng-click due to photoswipe gallery and socialshare. I want to add custom FB share, and if I use ng-click it will close the photoswipe opened image. Please see the example here. Open an image and click on the top-left custom share button

Note, even if I use the example here, it will not bind my $scope.name to the html.

If I try to log the value it works as a charm, eg.

console.log($scope.name); //will work perfectly

In the html it will not bind the value:

<div ng-controller="myController">
<button id="my-id">
   <p>{{name}}</p>
</button>
</div>
3
  • You should never directly interact with the DOM from controllers (i.e. no document.getElement...). This question is answerable per se (digest cycle is being bypassed), but to get a real Angular answer you need to change your approach. For that we'd need to know what problem you have with ng-click. Commented Feb 15, 2016 at 9:48
  • To update the scope out of angulars domain (native click handler, jQuery callback) use $scope.$apply but as @deceze said your doing it wrong this way. Commented Feb 15, 2016 at 9:49
  • I'd suggest you to open a new question with details about the issue between ng-click and photoswipe; it's too vague what exactly the issue is, but I'm pretty sure there's no reason it can't be solved. Commented Feb 15, 2016 at 10:09

1 Answer 1

5

For a topical solution, the problem is that a plain event listener will bypass the digest cycle. That means your $scope is getting updated, but Angular doesn't know about it, because the event which triggered the update is not on Angular's radar, and hence Angular doesn't update the template. The (bad) solution to this problem is to use $scope.$apply to forcefully trigger a digest.

But again, this is an un-Angular solution and you'd be off a lot better if you fixed whatever problem you have with ng-click instead.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.