Use $scope variable in a JavaScript function calle

2019-06-09 00:58发布

问题:

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!

回答1:

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.



回答2:

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



回答3:

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
}


回答4:

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.