I'm using Angular and I'm trying to get $scope to use it in a JavaScript function. Here is an example:
I have an html tag something like this:
<a id="doSomething" onclick="javascript: doSomething(this);">Do Something</a>
<div ng-show="flag">Click!</div>
and a JavaScript function something like this:
function doSomething(obj) {
//$scope.flag = true;
return true;
}
What I want is to use the $scope in this function. I haven't found a way to inject it. The thing is that I must use this way to call the function. Do you have any solution to this? I would appreciate it!
Thanks!
This is the same as @Andy's answer, but I mention it in case people want to see how to get the $scope from an event instead of
this
:HTML:
JS:
You can also do it inline:
JS:
HTML:
Caveat - scope nesting may affect the results but if the angular code is in the parent controlled this works fine out the box
You should call angular ng-click for this and then pass scope from there.
Here is the example i created for you. http://plnkr.co/edit/UDLJYuZhR4yfiocSPjKJ
Mark it as answer if it solves your problem.
If you really have to.. here's how:
HTML:
JS:
Make sure to read the docs for angular.element: http://docs.angularjs.org/api/angular.element And for scope.$apply: http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply
What is your use case, though? There might be a better way.