1

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!

4 Answers 4

4

If you really have to.. here's how:

HTML:

<a onclick="doThing(this);">Do it!</a>

JS:

function doThing(el) {
  var $scope = angular.element(el).scope();
  $scope.thing = newVal;
  $scope.$apply(); //tell angular to check dirty bindings again
}

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.

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

1 Comment

This doesn't work: "Uncaught ReferenceError: doThing is not defined"
1

You can also do it inline:

JS:

$scope.doThis = function(str){
     alert(str);
     $scope.$apply();
}

HTML:

<button onclick="angular.element(this).scope().doThis('TEST');"></button>

Caveat - scope nesting may affect the results but if the angular code is in the parent controlled this works fine out the box

Comments

0

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:

<a onclick="doThing(event);">Do it!</a>

JS:

function doThing(ev) {
  var $scope = angular.element(ev.srcElement).scope();          
  $scope.flag = true;
  $scope.$apply(); //tell angular to check dirty bindings again
}

1 Comment

ev.srcElement = undefined
0

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.

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.