Levi F.
Levi F.

Reputation: 91

How to get $scope from inside a controller function?

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>

Upvotes: 0

Views: 280

Answers (1)

deceze
deceze

Reputation: 522175

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.

Upvotes: 5

Related Questions